Nodes and next pointers
In Python a node is a small object with two attributes: val and next. The list itself is just a reference to the first node, the head. The last node's next is None. There is no index: to reach the third node you start at the head and follow next twice.
Insertion: stop one node early
To insert 3 at position 2, you need the node before that position, because that is the node whose next pointer has to change. The loop walks prev forward index - 1 times, to the node holding 2. Then two pointer changes splice the new node in:
node.next = prev.next: the new node points at 4, the rest of the list.prev.next = node: 2 now points at the new node.
The order matters. Do the second line first and the only reference to 4 and 5 is gone: they are cut off, and the list ends at 3.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertAt(head, index, val):
node = ListNode(val)
if index == 0:
node.next = head
return node
prev = head
for _ in range(index - 1):
prev = prev.next
node.next = prev.next
prev.next = node
return head
Reversal: three pointers, one loop
Reversing a linked list in place turns every next pointer around. You need three names: prev (the part already reversed), curr (the node being turned), and nxt (the rest of the list, saved before the pointer is overwritten). Each pass of the loop:
| Pass | Saves nxt | Turns | Then prev, curr |
|---|---|---|---|
| 1 | 2 | 1.next → None | 1, 2 |
| 2 | 3 | 2.next → 1 | 2, 3 |
| 3 | None | 3.next → 2 | 3, None |
Forget to save nxt and the moment curr.next = prev runs, the rest of the list is unreachable.
def reverseList(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
What you see in PyVisualizer
The list is drawn as nodes and arrows, and every variable that refers to a node (head, prev, curr, nxt) is a label on the node it points to. When a line changes a next pointer, that arrow swings to its new target; when a variable moves, its label moves with it. A pointer change that cuts the chain shows it cut: the two parts are drawn apart, so you can see which part each variable still reaches.
Common mistakes
- Losing the rest of the list by overwriting a
nextpointer before saving what it pointed to. - Stopping on the wrong node. To change the link into position i you need node i − 1. Walking one step too far is the classic off-by-one.
- Forgetting the empty list and the head. Inserting at position 0, or into
None, has no node before it: the function has to return the new head. - Returning the old head after a reversal. It is now the last node; the new head is
prev.
Try it yourself
- Insert at position 0, then at the end, and see which lines run.
- Paste a LeetCode linked-list solution: give the list as [1, 2, 3] and it is built from ListNode objects for you.