linkedlist in c++
#include <iostream>
class Node {
public:
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
class LinkedList {
public:
Node* head;
LinkedList() {
head = nullptr;
}
// Function to insert a new node at the beginning of the linked list
void insertAtBeginning(int val) {
Node* newNode = new Node(val);
newNode->next = head;
head = newNode;
}
// Function to display the linked list
void display() {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
};
int main() {
LinkedList list;
list.insertAtBeginning(3);
list.insertAtBeginning(7);
list.insertAtBeginning(12);
list.display();
return 0;
}
Explanation:
- The program defines a Node
class representing a node in a linked list. It contains two members: data
to store integer data and next
to point to the next node in the list.
- A LinkedList
class is defined to manage the linked list. It contains a head
pointer initially set to nullptr
.
- insertAtBeginning
function in LinkedList
class inserts a new node at the beginning of the linked list. It creates a new node with the given value and adjusts pointers to include the new node at the start.
- display
function in LinkedList
class traverses the linked list starting from the head and prints the data of each node.
- In the main
function, a LinkedList
object list
is created. Nodes with values 3, 7, and 12 are inserted at the beginning of the list using insertAtBeginning
.
- Finally, the display
function is called to print the contents of the linked list.