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 very front of a row of books on a shelf, pushing the others back.
null ā head
null ā head
10 -> null ā newNode
10 -> null ā newNode
10 -> null ā head
10 -> null ā head
public class LinkedList { static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } Node head; // Insert new node at beginning public void insertAtBeginning(int value) { Node newNode = new Node(value); // create new node newNode.next = head; // link new node to current head head = newNode; // update head to new node } // Print list public void printList() { Node curr = head; while (curr != null) { System.out.print(curr.data + " -> "); curr = curr.next; } System.out.print("null\n"); } public static void main(String[] args) { LinkedList list = new LinkedList(); list.insertAtBeginning(10); list.printList(); } }
Node newNode = new Node(value); // 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
list with value 5?new Node(5, list.head) creates a new node pointing to current head.list.head = new Node(5, list.head); inserts at beginning correctly.class Node {
int data;
Node next;
Node(int d, Node n) { data = d; next = n; }
}
Node head = new Node(3, null);
head = new Node(2, head);
head = new Node(1, head);
// Print list
Node temp = head;
while(temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.print("null");class Node {
int data;
Node next;
Node(int d) { data = d; next = null; }
}
Node head = null;
Node newNode = new Node(10);
newNode.next = head.next;
head = newNode;head.next access is invalid and causes error.newNode.next = head.next; throws NullPointerException because head is null.class Node {
int data;
Node next;
Node(int d) { data = d; next = null; }
}
Node head = new Node(4);
head.next = new Node(5);
head.next.next = new Node(6);
// Insert new node with value 3 at beginning and print list
// Fill in the blanks below
// Insert code here
// Print code here
Pass the test and this pattern moves unknown