struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* head = new Node(1);
head->next = new Node(2);
Node* temp = new Node(3);
temp->next = head->next;
head->next = temp;
Node* curr = head;
while (curr != nullptr) {
std::cout << curr->data << " -> ";
curr = curr->next;
}
std::cout << "null";The new node with value 3 is inserted between nodes with values 1 and 2. So the list becomes 1 -> 3 -> 2 -> null.
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
Node* prev = nullptr;
Node* curr = head;
Node* next = nullptr;
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " -> ";
temp = temp->next;
}
std::cout << "null";The code reverses the linked list by changing the next pointers to point backward. The original list 10 -> 20 -> 30 -> null becomes 30 -> 20 -> 10 -> null.
A doubly linked list node needs two pointers: one to the previous node and one to the next node to allow traversal in both directions.
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* head = nullptr;
Node* newNode = new Node(5);
newNode->next = head;
head = newNode;
// Insert another node
Node* anotherNode = new Node(10);
head->next = anotherNode;
anotherNode->next = nullptr;
// Incorrect insertion
Node* wrongNode = new Node(15);
wrongNode->next = head;
head = wrongNode;
head->next->next = nullptr;The last insertion sets head to wrongNode (15), whose next points to old head (5). But then head->next->next is set to nullptr, which breaks the link to node 10, losing it from the list.
A circular singly linked list requires only one pointer per node (next). The last node's next points back to the head, forming a circle.
