Walking a list
After this: Walk a list from the head to the end by following next.
On this page · 7 sections · 4 checks
In the treasure hunt, the only way to reach the third clue was to read the first two. A linked list works the same way. Suppose you are handed one pointer, to a node holding 3. How much of the list can you see?
You can see all of it, but only one node at a time. This lesson shows how a program goes through a list, and what that costs.
One node at a time
You know the parts already. The head points at the first node. Each node's next points at the node after it. The last node's next is Nonenull. A list does not store its length anywhere, so the only way to find the end is to reach that Nonenull.
To go through a list we use a variable, usually called cur, short for current. Think of cur as your finger on the node you are reading. Here is the walk on 3 → 7 → 9.
- Set
curto head.curis on 3, so read 3. - Set
curtocur.next.curis on 7, so read 7. - Set
curtocur.next.curis on 9, so read 9. - Set
curtocur.next. Thenextof 9 is Nonenull, socuris now Nonenull and the walk stops.
The important line is cur = cur.next. It reads the pointer stored in the current node, and moves cur to the node that pointer leads to. It does not change any node. Only the variable moves.
Going through a list like this is called a . Books and documentation often say traversal, which means the same thing.
Here is the walk as code. It is the same four steps, written as a loop.
cur = head # start at the first nodewhile cur is not None: # None means we have passed the last node print(cur.value) cur = cur.next # move to the next node3 7 9
Node cur = head; // start at the first nodewhile (cur != null) { // null means we have passed the last node System.out.println(cur.value); cur = cur.next; // move to the next node}3 7 9
The loop test runs before every step. When cur is Nonenull, the loop stops, so the code never tries to read a value from nothing.
Two helpers
From here on, two small functions save us some typing. build makes a list from some values, and show turns a list into text so that we can print it.
def build(values): head = None for v in reversed(values): # link from the back: each new node points at the rest head = Node(v, head) return head
def show(head): out = [] cur = head # start at the head; there is no other way in while cur is not None: # None marks the end out.append(str(cur.value)) cur = cur.next # follow the pointer return " -> ".join(out)static Node build(int... values) { Node head = null; for (int i = values.length - 1; i >= 0; i--) { // link from the back: each new node points at the rest head = new Node(values[i], head); } return head;}
static String show(Node head) { StringBuilder out = new StringBuilder(); Node cur = head; // start at the head; there is no other way in while (cur != null) { // null marks the end if (out.length() > 0) out.append(" -> "); out.append(cur.value); cur = cur.next; // follow the pointer } return out.toString();}show is the walk you have seen, except that it collects the values into one piece of text and does not print them.
build goes through the values from last to first, because each new node has to point at the rest of the list, and the rest has to exist first. The int... values part lets you pass any number of values, as in build(3, 7, 9). Here is build on 3, 7 and 9.
- head starts as Nonenull, so the list is empty.
- Take 9. Make a node whose
nextis head, which is nothing. Move head to this node. The list is 9. - Take 7. Make a node whose
nextis head, which is the 9 node. Move head to this node. The list is 7 → 9. - Take 3. Make a node whose
nextis head, which is the 7 node. Move head to this node. The list is 3 → 7 → 9.
Finding a value, and finding the last node
Two common jobs are both walks. They differ only in when they stop.
- To find a value, walk until a node holds that value.
- To find the last node, walk until
nextis Nonenull. The last node of a list is called the .
def find(head, target): cur = head while cur is not None: if cur.value == target: return cur # the node itself, not an index cur = cur.next return None # walked off the end: not there
def append(head, value): new = Node(value) if head is None: return new cur = head while cur.next is not None: # walk to the tail: the node whose next is None cur = cur.next cur.next = new # one pointer write, after a walk of n return headstatic Node find(Node head, int target) { Node cur = head; while (cur != null) { if (cur.value == target) return cur; // the node itself, not an index cur = cur.next; } return null; // walked off the end: not there}
static Node append(Node head, int value) { Node node = new Node(value); if (head == null) return node; Node cur = head; while (cur.next != null) cur = cur.next; // walk to the tail: the node whose next is null cur.next = node; // one pointer write, after a walk of n return head;}Here is how to read it.
findis the walk with oneifadded. It returns the node itself, not an index, because a linked list has no indexes.- If the walk reaches the end, the value is not in the list, so
findreturns Nonenull. appendadds a node at the end. It makes the new node first. If the list is empty, the new node is the whole list.- Otherwise
appendwalks to the tail. This loop testscur.next, notcur, so it stops on the last node and does not run past it. - The last step is one pointer write: the old tail now points at the new node.
appendreturns the head, and the caller writeshead = append(head, 11). That is how an empty list gets its first node.
head = build([3, 7, 9])print(show(head))print(find(head, 7).value, find(head, 8))head = append(head, 11)print(show(head))3 -> 7 -> 9 7 None 3 -> 7 -> 9 -> 11
Node head = build(3, 7, 9);System.out.println(show(head));System.out.println(find(head, 7).value + " " + find(head, 8));head = append(head, 11);System.out.println(show(head));3 -> 7 -> 9 7 null 3 -> 7 -> 9 -> 11
What a walk costs
The longer the list, the longer a walk can take. In the worst case, a walk visits every node, so its cost is O(n): the work grows with the size of the list. Finding a value is O(n). Appending is O(n) as well if you keep only the head, even though the write at the end is one pointer, because the tail has to be found first.
Watch it happen
The program searches for a value that is in the list, then for one that is not, and then appends.
- Search for 9Search for 9. Start at head, compare, then follow next. The third node takes three comparisons.
- Search for 8
- Append 11
Run an operation to begin.
It took three comparisons to find 9, the third node. It also took three comparisons to learn that 8 is not there, because the walk stops only when next is empty. Appending 11 walked all three nodes to find the tail, and then made one pointer write.
Check yourself
head is the node 3 in 3 → 7 → 9. What is head.next.next.value?
How does a walk know it has reached the end of a linked list?
A linked list of n nodes has only a head pointer. What does appending at the end cost, and why?
What does this print?
head = build([3, 7, 9])print(show(head))print(find(head, 7).value, find(head, 8))head = append(head, 11)print(show(head))Node head = build(3, 7, 9);System.out.println(show(head));System.out.println(find(head, 7).value + " " + find(head, 8));head = append(head, 11);System.out.println(show(head));Connect
- Walk a list from the head with cur = cur.next, and stop at the end marker (None in Python, null in Java).
- Find a value or the tail by walking, and say when each walk stops.
- Say why appending is O(n) when you keep only a pointer to the head.