Builds onLinked list basics
01The idea
A linked list has no index, so you cannot go to the middle or the end in one step. A few pointer tricks get around that. Each one walks the list once with two or three pointers and uses O(1) extra space.
- Slow and fast pointers. Both start at the head. Each round, slow moves one node and fast moves two. When fast reaches the end, slow is at the middle. If the list has a cycle, fast never reaches an end. It laps slow, and the two meet inside the cycle.
- A gap between two pointers. Move one pointer k nodes ahead, then move both one node at a time. When the front pointer reaches the end, the back pointer is k nodes from the end.
- Reversing in place. Walk with
prev,currandnext. Savecurr.next, pointcurr.nextback atprev, then move both pointers forward. Every arrow flips in one pass. - A dummy head when building a new list, as in the linked list basics lesson.
Harder list problems are two or three of these in a row. To check whether a list reads the same both ways, find the middle, reverse the second half, then compare the halves.
02How to spot it
Use these tricks when the input is a linked list and the problem asks for:
- the middle node, or the list split into halves
- whether there is a cycle, or where it starts
- the kth node from the end
- the list reversed, in full or in parts
- O(1) extra space, which rules out copying the values into an array
The brute force counts the list in one pass and then walks it again. That works too, and it is still O(n). The tricks matter when you must do it in one pass, or when there may be a cycle and counting would never stop.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue