Singly linked list
easy 18 minA singly linked list is a chain of nodes where each node holds a value and a pointer to the next node.
See it run
Insert, delete, search, traverse and reverse a chain of nodes joined by next pointers, then the same moves in trains, treasure hunts, playlists and hash tables.
Operations
Insert at head
Create a node, point its next at the current head, then move head to the new node.
Step 1 of 4
The list before
HEAD → 10 → 20 → 30 → NULL. We want to insert 5 at the head.
Step 1: The list before
def insert_head(self, value): new_node = Node(value) new_node.next = self.head # point at the old head self.head = new_node # head moves to the new node- Time
- O(1)
- Space
- O(1)
- vs array insert at front
- O(n) shift
O(1) with no traversal. This is where linked lists beat arrays, which must shift every element.
In the real world
The same singly linked list doing real jobs. Pick one and step through it.
Each car (node) has a coupler (next pointer) to the car behind it. The engine is the head.
Step 1 of 6
A train is a linked list
The engine leads, each car is coupled to the next, and the last coupler hangs free like NULL. Adding or removing a car means connecting or disconnecting a coupler; nothing else moves.
Step 1: A train is a linked list
train = ["Engine", "Car 1", "Car 2", "Car 3"]# couple a new engine at the front: O(1)# walk to car 3: pass through every car before it, O(n)# uncouple the last car: find the car before it, O(n)Common mistakes
The bugs interviewers watch for, with the fix beside each.
Losing the next reference
criticalOnce you overwrite current.next, the rest of the list is gone unless you saved it first.
Wrongcurrent.next = prevcurrent = current.next # this is prev now: the rest is lostRightnext_node = current.next # save it firstcurrent.next = prevcurrent = next_nodeNot handling an empty list
criticalReading head.val or head.next when head is None raises AttributeError.
Wrongdef get_first(head): return head.val # crashes on NoneRightdef get_first(head): if head is None: return None # or raise an error return head.valOff by one when walking to a position
majorInsert and delete need the node before the target, because that is the node whose next changes.
Wrongfor _ in range(pos): # lands ON the target current = current.nextRightfor _ in range(pos - 1): # stops one before it current = current.next# current.next is the targetForgetting to update head
criticalThe head must always point at the first node; otherwise the new node is unreachable.
Wrongnew_node = Node(value)new_node.next = head# head still points at the old first nodeRightnew_node = Node(value)new_node.next = headhead = new_nodeNot returning the new head
criticalAssigning head inside a function changes only the local name. The caller keeps the old head.
Wrongdef reverse(head): ... head = prev # caller never sees thisRightdef reverse(head): ... return prevhead = reverse(head)Looping forever on a cycle
majorA plain walk never reaches None if the list loops. Use Floyd's slow and fast pointers.
Wrongwhile current: current = current.next # never ends on a cycleRightslow = fast = headwhile fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return Truereturn FalseConfusing node identity with value
majorTwo nodes can hold the same value. Use is for the same node and .val for equal values.
Wrongif node1 == node2: # unclear: identity or value? print("same")Rightif node1.val == node2.val: # equal values print("same value")if node1 is node2: # the same node print("same node")Writing == None
minorIt works, but is None is the Python idiom: clearer and immune to custom __eq__.
Wrongif current == None: returnwhile current.next != None: current = current.nextRightif current is None: returnwhile current.next is not None: current = current.next
Interview tips
Reach for it when
- You insert or delete at the head often
- You build a stack or a queue
- An LRU cache needs O(1) moves (with a hash map)
- You splice or merge lists
- Polynomial terms or sparse data
Avoid it when
- You need O(1) access by index: use an array
- You need binary search: use a sorted array
- Memory is tight: every node carries a pointer
- Cache speed matters: arrays are contiguous
Must-know patterns
- Slow and fast pointers: middle, cycle, nth from end
- Dummy node: no special case for the head
- Reversal: whole list, in groups of k, palindrome check
- Merge: two sorted lists, k sorted lists
- Draw the arrows before you code
Always test
- Empty list (head is None)
- One node and two nodes
- Operation at the head
- Operation at the tail
- A list with a cycle