Mental Model
Add a new item right at the start so it becomes the first thing in the list.
Analogy: Imagine putting a new book on the front of a stack so it is the first one you see.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
new_node(0) -> null head -> 1 -> 2 -> 3 -> null
new_node(0) -> 1 -> 2 -> 3 -> null head -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
#include <iostream> using namespace std; struct Node { int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; class LinkedList { public: Node* head; LinkedList() : head(nullptr) {} void insertAtBeginning(int val) { Node* newNode = new Node(val); // create new node newNode->next = head; // link new node to current head head = newNode; // update head to new node } void printList() { Node* curr = head; while (curr != nullptr) { cout << curr->data << " -> "; curr = curr->next; } cout << "null" << endl; } }; int main() { LinkedList list; list.insertAtBeginning(3); list.insertAtBeginning(2); list.insertAtBeginning(1); cout << "Before insertion:" << endl; list.printList(); list.insertAtBeginning(0); cout << "After inserting 0 at beginning:" << endl; list.printList(); return 0; }
Node* newNode = new Node(val); // create new nodenewNode->next = head; // link new node to current headhead = newNode; // update head to new nodenewNode->next = head; // link new node to current head
head = newNode; // update head to new node
struct Node { int data; Node* next; };
Node* head = nullptr;
Node* newNode = new Node{10, nullptr};
newNode->next = head;
head = newNode;
newNode = new Node{20, nullptr};
newNode->next = head;
head = newNode;Node* newNode = new Node(); newNode->data = 5; head = newNode; newNode->next = head;
Pass the test and this pattern moves unknown