Certainly! Let's walk through the execution of the provided reverseList function step by step using the input linked list 1 -> 2 -> 3 -> null.
Initial Setup:
-
Linked List Nodes:
node1: value = 1, next = node2
node2: value = 2, next = node3
node3: value = 3, next = null
-
Variable Initialization:
prev = null
current = head (node1)
Visual Representation Before Reversal:
[1] -> [2] -> [3] -> null
Step 1
Current Node: node1 (value 1)
Operations:
-
Save Next Node:
nextTemp = current.next
= node1.next
= node2
-
Reverse Current Node's Pointer:
current.next = prev
= node1.next = null
Effect: Node 1 now points to null.
-
Move prev to Current Node:
prev = current
= node1
-
Move to Next Node:
current = nextTemp
= node2
Linked List State:
-
Reversed Part:
[1] -> null
-
Remaining Part:
[2] -> [3] -> null
Visual Representation:
prev (reversed): [1] -> null
current (to process): [2] -> [3] -> null
Step 2
Current Node: node2 (value 2)
Operations:
-
Save Next Node:
nextTemp = current.next
= node2.next
= node3
-
Reverse Current Node's Pointer:
current.next = prev
= node2.next = node1
Effect: Node 2 now points to node1.
-
Move prev to Current Node:
prev = current
= node2
-
Move to Next Node:
current = nextTemp
= node3
Linked List State:
-
Reversed Part:
[2] -> [1] -> null
-
Remaining Part:
[3] -> null
Visual Representation:
prev (reversed): [2] -> [1] -> null
current (to process): [3] -> null
Step 3
Current Node: node3 (value 3)
Operations:
-
Save Next Node:
nextTemp = current.next
= node3.next
= null
-
Reverse Current Node's Pointer:
current.next = prev
= node3.next = node2
Effect: Node 3 now points to node2.
-
Move prev to Current Node:
prev = current
= node3
-
Move to Next Node:
current = nextTemp
= null
Linked List State:
Visual Representation:
prev (reversed): [3] -> [2] -> [1] -> null
current (to process): null
Termination
Since current is now null, we exit the while loop.
Final Reversed Linked List Head:
prev: [3] -> [2] -> [1] -> null
Function Returns:
return prev
Final Output
The linked list has been reversed, and the new head is node3. The reversed linked list is:
[3] -> [2] -> [1] -> null
Visual Representation of Reversed List:
[3] -> [2] -> [1] -> null
Summary of Variable Changes
| Step | current | nextTemp | prev | Action |
|---|
| 1 | node1 | node2 | null | Reverse node1.next, move prev to node1 |
| 2 | node2 | node3 | node1 | Reverse node2.next, move prev to node2 |
| 3 | node3 | null | node2 | Reverse node3.next, move prev to node3 |
| End | null | N/A | node3 | Return prev as new head |
Understanding the Reversal Process:
At each step, the current node's next pointer is reversed to point to the previous node (prev). Then, prev moves forward to become the current node before the reversal, and current moves to the next node in the original list.
By iteratively applying these steps, the linked list is reversed in place without using extra space for a new list.