Singly linked lists
Implement a singly linked list and reverse, merge and split lists with pointer manipulation.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
A singly linked list is a chain of nodes where each node holds a value and a pointer to the next node. Inserting or removing at the head is O(1), but reaching index i takes O(i) steps. Most linked list problems are careful pointer rewiring, made simpler with a dummy head node.
Think of it like this: A treasure hunt where each clue tells you only where the next clue is.
Explained simply
An array keeps its items side by side in memory, like houses on one street with numbers. A linked list is different. Each item lives in its own small box called a node, which can be anywhere in memory. Every node holds a value and an arrow, called a pointer, to the next node.
To use the list you only need the first node, the head. From there you follow the arrows one by one until an arrow points to nothing (None in Python). That last node is the tail.
This makes some jobs very cheap and others slow. Adding a node at the front is instant: make it point to the old head, and it becomes the new head. But finding the 500th item means walking 499 arrows, because there is no way to jump straight there.
Most linked list problems in interviews are about rewiring arrows without losing any nodes. Draw boxes and arrows on paper, change one arrow at a time, and always save the node you are about to lose before you overwrite its pointer.
Press Play on a diagram to walk through it one step at a time.
- 1Start
prev = None, cur = head
- 2Save next
nxt = cur.next
- 3Flip pointer
cur.next = prev
- 4Advance
prev = cur, cur = nxt
- 5Finish
When cur is None, prev is the new head.
- Index access: O(1)
- Append at end: amortised O(1)
- Insert or delete at front: O(n)
- Items next to each other in memory
- Index access: O(n)
- Insert or delete at head: O(1)
- Insert after a held node: O(1)
- Nodes scattered, one pointer each
In depth
Node and list classes, and what each operation costs
A Node holds val and next. A small LinkedList wrapper usually stores head, an optional tail and a size counter, so len() is O(1) instead of a full walk.
Insert at head is O(1): new.next = head, then head = new. Insert at tail is O(1) only if you keep a tail pointer; without it you must walk the whole list, O(n). Delete at head is O(1). Delete at tail is O(n) even with a tail pointer, because you need the node before the tail, and a singly linked list cannot step backwards. Insert or delete after a node you already hold is O(1). Search by value or by index is O(n).
In Python, adding __slots__ = ('val', 'next') to the Node class stops each node from carrying its own attribute dictionary, which saves a lot of memory for long lists.
- Head insert or delete: O(1)
- Tail insert: O(1) with a tail pointer, else O(n)
- Tail delete: O(n), needs the previous node
- Access by index or search: O(n)
Reversing recursively, and what it really costs
The recursive reversal reads like a definition: reverse the rest of the list, then put the current node at the end of that reversed rest. The base case is an empty list or a single node, which is already reversed. After the recursive call returns new_head, head.next is the last node of the reversed rest, so head.next.next = head attaches head behind it, and head.next = None makes head the new tail.
The time is O(n), the same as the loop. The space is not: each call waits on the call stack until the deeper calls finish, so it uses O(n) stack frames. CPython's default recursion limit is 1000, so reversing a list of a few thousand nodes this way raises RecursionError. That is why the iterative O(1)-space version is the one to use in real code, and the recursive one is mainly a good test of recursive thinking.
The dummy head node and merging sorted lists
Many list operations treat the head as a special case: deleting the first node, inserting before it, or building a result list from nothing. A dummy node is a throwaway node placed in front of the real head. Now every real node has a node before it, so one loop handles every case, and the answer is dummy.next.
Merging two sorted lists shows the idea clearly. Keep a tail pointer that starts at the dummy. Compare the two front nodes, attach the smaller one to tail, move forward in that list, and move tail forward. When one list runs out, attach the rest of the other in one step, because it is already sorted. This takes O(n + m) time and O(1) extra space, since it reuses the existing nodes instead of creating new ones. Using <= when comparing keeps equal values in their original order, which makes the merge stable.
- 1Start
tail = dummy; fronts are 1 and 2
- 2Take 1
dummy -> 1; fronts 3 and 2
- 3Take 2
-> 1 -> 2; fronts 3 and 4
- 4Take 3, then 4
-> 1 -> 2 -> 3 -> 4; second list empty
- 5Attach rest
tail.next = 5 in one step
- 6Return dummy.next
1 -> 2 -> 3 -> 4 -> 5
Two pointers with a gap, and splitting
Because you cannot index into a list, many problems use two pointers moving through it together. To find the k-th node from the end in one pass, move a fast pointer k steps ahead first, then move both pointers one step at a time. When fast reaches the end, slow is exactly k nodes behind it. Starting both at a dummy node makes removing the first node work with no special case.
Splitting a list in two is just cutting one pointer: walk to the node where the first part should end, save its next as the head of the second part, then set its next to None. Splitting at the middle plus merging gives merge sort for linked lists, which runs in O(n log n) time and needs no random access, so it suits lists better than quicksort does.
- k-th from end: gap of k between two pointers
- Split: save next, then set next = None
- Merge sort on a list: O(n log n), O(log n) recursion stack
Linked list or array: the honest trade-off
On paper, linked lists win at inserting in the middle: O(1) once you hold the node, while an array must shift elements, O(n). In practice arrays are often faster anyway. Array elements sit next to each other in memory, so the CPU cache loads many at once. Linked nodes are scattered, so each step can be a cache miss, and every node also pays for a pointer.
That is why Python's list is a dynamic array and there is no linked list in the standard library. Linked structures shine when you already hold references to nodes and must splice them in O(1): LRU caches, free lists in memory allocators, adjacency lists, and the hash table chains you meet in the hashing module.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Implement node and list classes~40m
- 2Insert and delete at head and tail~40m
- 3Reverse a list iteratively and recursively~40m
- 4Use a dummy head node~40m
- 5Merge two sorted lists~40m
Key points
- Insert or delete at head: O(1); at tail: O(1) only if you keep a tail pointer.
- Access or search by position: O(n).
- Reversal is O(n) time and O(1) space iteratively.
- A dummy node removes special cases when the head might change.
Key terms
Tap a card to flip it. 0/4 known
Examples
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def reverse(head): # O(n) time, O(1) space
prev, cur = None, head
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
head = reverse(Node(1, Node(2, Node(3))))
while head:
print(head.val, end=' '); head = head.next # 3 2 1Merge two sorted lists
Input: 1 -> 3 -> 5 and 2 -> 4. Step 1: create a dummy and point tail at it. Step 2: while both lists have nodes, attach the smaller front node and advance. Step 3: attach whatever is left. Step 4: return dummy.next. No new value nodes are created; the existing nodes are relinked, so extra space is O(1) and time is O(n + m).
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def merge(a, b): # O(n + m) time, O(1) extra space
dummy = tail = Node(0)
while a and b:
if a.val <= b.val:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b
return dummy.nextRemove the n-th node from the end in one pass
List 1 -> 2 -> 3 -> 4 -> 5, n = 2, so node 4 must go. Step 1: put fast and slow on a dummy before the head. Step 2: move fast n steps ahead, to node 2. Step 3: move both until fast is on the last node; slow is now on node 3, just before the target. Step 4: skip the target with slow.next = slow.next.next. The dummy makes removing the real head (n equal to the length) work with the same code. O(L) time, O(1) space.
def remove_nth_from_end(head, n):
dummy = Node(0, head)
fast = slow = dummy
for _ in range(n):
fast = fast.next
while fast.next:
fast, slow = fast.next, slow.next
slow.next = slow.next.next
return dummy.nextQuick reference
- Head insert and delete: O(1). Tail insert: O(1) only with a tail pointer
- Tail delete in a singly linked list is O(n): you need the previous node
- Iterative reverse: O(n) time, O(1) space. Recursive reverse: O(n) stack space
- Use a dummy node whenever the head might change; return dummy.next
- Merging two sorted lists: O(n + m) time, O(1) extra space
- k-th from end: advance fast k steps, then move both until fast ends
- Save cur.next before you overwrite it, or the rest of the list is lost
Common mistakes
- Losing the rest of the list by overwriting next before saving it.
- Forgetting to handle empty and single-node lists.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write from_list(values) that builds a linked list from a Python list, and to_list(head) that turns it back into a Python list.
- Exercise 2medium
Reverse a linked list recursively, and explain why it fails for a list of 5,000 nodes in default CPython.
- Exercise 3hard
Check whether a linked list is a palindrome in O(n) time and O(1) extra space.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Python have a built-in linked list?
- Not as a public type. list is a dynamic array, and collections.deque is built from linked blocks but does not expose nodes. For algorithm practice you write a small Node class.
- When should I use a linked list instead of an array?
- When you hold references to nodes and must insert, remove or move them in O(1), as in an LRU cache. For most other jobs an array is simpler and faster because of memory locality.
- Why are linked lists so common in interviews?
- They test careful pointer handling, edge cases like empty and one-node lists, and the ability to reason about O(1) space solutions.