Concept Flow - Push Using Linked List Node
Create new node with data
Set new node.next to current head
Update head to new node
Done
This flow shows how a new node is created and added at the start of the linked list by adjusting pointers.
Node newNode = new Node(10);
newNode.next = head;
head = newNode;| Step | Operation | Nodes in List | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Create new node with data=10 | None | newNode=Node(10) | 10 -> null |
| 2 | Set newNode.next = head (head=null) | None | newNode.next=null | 10 -> null |
| 3 | Update head = newNode | 10 | head points to newNode | head -> 10 -> null |
| 4 | Push complete | 10 | head points to 10 | head -> 10 -> null |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| head | null | null | null | points to newNode(10) | points to 10 |
| newNode | null | Node(10) | Node(10) with next=null | Node(10) with next=null | Node(10) with next=null |
Push Using Linked List Node: - Create new node with data - Set newNode.next = current head - Update head = newNode - New node becomes first element - Works even if list is empty
push operation do in a linked list when using nodes?new Node(data) to create a node with the given data.newNode.next = head and then head = newNode to push at front.class Node {
int data;
Node next;
Node(int d) { data = d; next = null; }
}
Node head = null;
// Push 10
Node newNode = new Node(10);
newNode.next = head;
head = newNode;
// Push 20
newNode = new Node(20);
newNode.next = head;
head = newNode;
// Push 30
newNode = new Node(30);
newNode.next = head;
head = newNode;
// Print list
Node temp = head;
while(temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.print("null");void push(int data) {
Node newNode = new Node(data);
newNode.next = null;
head = newNode;
}Pass the test and this pattern moves unknown