Builds onBig-O and complexity
01The idea
A linked list is a chain of nodes. Each node holds a value and a pointer called next to the node after it. The last node points to None, or null in Java. You hold the list by its first node, the head.
A linked list is different from an array in two ways:
- There is no index. To reach the fifth node, you start at the head and follow
nextfour times. That is O(n). - Inserting or removing a node is O(1), once you stand on the node before it. You only change one pointer. Nothing shifts.
To remove a node, change the next of the node before it so it skips over the node:
prev.next = prev.next.next
That is why most list code walks with a pointer that stops one node early. It looks at prev.next instead of the node it stands on.
The head has no node before it. A dummy node fixes that. Put a fake node in front of the head, do the work, and return dummy.next. Then the head is not a special case, even when the head itself gets removed.
02How to spot it
You will meet linked lists when:
- the input is given as a
ListNodehead - the problem asks you to remove, insert or reorder nodes without making new ones
- the problem asks for "O(1) extra space" on a list, so you must change pointers instead of copying values into an array
Reach for a dummy node whenever the head might change: removing nodes, merging two lists, or building a new list node by node.
Before you change a pointer, ask what you lose. If you overwrite node.next, the rest of the list is gone unless another variable still points at it.
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