Concept Flow - Insert at Beginning Head Insert
Create new node
Set new_node.next = head
Update head = new_node
Done
Insert a new node by creating it, pointing it to the current head, then updating head to this new node.
Node newNode = new Node(5);
newNode.next = head;
head = newNode;| Step | Operation | Nodes in List | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Create new node with data=5 | 10 -> 20 -> 30 -> null | newNode created with data=5, next=null | āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:10ā ā data:20ā ā data:30ā ā next:āāā¼āāā ā next:āāā¼āāā ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| 2 | Set newNode.next = head | 10 -> 20 -> 30 -> null (newNode not yet in list) | newNode.next points to node with data=10 | newNode: āāāāāāāāāā ā data:5 ā ā next:āāā¼āāā head (data:10) āāāāāāāāāā List unchanged: āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:10ā ā data:20ā ā data:30ā ā next:āāā¼āāā ā next:āāā¼āāā ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| 3 | Update head = newNode | 5 -> 10 -> 20 -> 30 -> null | head now points to newNode | āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:5 ā ā data:10ā ā data:20ā ā data:30ā ā next:āāā¼āāā ā next:āāā¼āāā ā next:āāā¼āāā ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| 4 | Done | 5 -> 10 -> 20 -> 30 -> null | No pointer changes | Final list: āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:5 ā ā data:10ā ā data:20ā ā data:30ā ā next:āāā¼āāā ā next:āāā¼āāā ā next:āāā¼āāā ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| head | points to node with data=10 | points to node with data=10 | points to node with data=10 | points to newNode (data=5) | points to newNode (data=5) |
| newNode | null | new node created with data=5, next=null | next points to head (data=10) | exists with next=head | exists with next=head |
Insert at Beginning (Head Insert): 1. Create new node with data. 2. Set newNode.next = current head. 3. Update head = newNode. Result: new node is first, old list follows. Works even if list is empty (head=null).
class Node {
public int data;
public Node next;
public Node(int d) { data = d; next = null; }
}
Node head = new Node(10);
head.next = new Node(20);
Node newNode = new Node(5);
newNode.next = head;
head = newNode;
Node temp = head;
while(temp != null) {
Console.Write(temp.data + " -> ");
temp = temp.next;
}
Console.WriteLine("null");Node newNode = new Node(15); newNode.next = newNode; head = newNode;
Pass the test and this pattern moves unknown