What this topic covers
24 subtopics- Cycle detection4
- Reversal4
- Deletion3
- Insertion3
- Library lists3
- Rearranging3
- Doubly linked lists2
- LRU cache2
- Merging2
- Recursion on lists2
- Slow and fast pointers2
- Traversal2
Show all 24 subtopics
- Two pointers2
- Access1
- Arithmetic on lists1
- Basics1
- Choosing a structure1
- Circular lists1
- Deep copy1
- Dummy nodes1
- Memory1
- Palindromes1
- Rotation1
- Sorting lists1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
A linked list trades random access for cheap insertion and deletion: each node holds a value and a pointer to the next node. Interview questions come down to careful pointer updates – save next before you overwrite it – and a few patterns: a dummy head to avoid special cases, slow and fast pointers for the middle and for cycles, and reversal. Lists are drawn below as boxes; the dot on each box is its next pointer.
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
What does this print?
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
head = Node(4, Node(8, Node(15)))
cur = head
while cur:
print(cur.val, end=' ')
cur = cur.next
Show answer and explanation
Explanation
Traversal follows next from the head until it reaches None, visiting nodes in list order.
Why the other options are wrong
- AThe loop continues while cur is not None.
- CNothing reverses the order.
- DThe last node is printed before cur becomes None.
Complete the iterative reversal so the program prints 4 3 2 1.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def build(vals):
head = None
for v in reversed(vals):
head = Node(v, head)
return head
def show(head):
out = []
while head:
out.append(head.val)
head = head.next
print(*out)
prev, cur = None, build([1, 2, 3, 4])
while cur:
nxt = cur.next
____________
prev, cur = cur, nxt
show(prev)
cur.next = nxt
nxt.next = cur
prev.next = cur
cur.next = prev
Show answer and explanation
Explanation
Save the rest of the list in nxt, point the current node backwards at prev, then advance both. O(n) time, O(1) space.
Why the other options are wrong
- ALeaves the links unchanged: prints only 4.
- BOn the first step it points node 2 back at node 1, making a two-node cycle – the loop never ends.
- Cprev is None on the first step – AttributeError.
Reverse the nodes in groups of k = 3; a final group shorter than k stays as it is. What is the result?
Show answer and explanation
Explanation
Groups [1, 2, 3] and [4, 5, 6] are reversed; [7, 8] has fewer than 3 nodes and is left alone. Each group is reversed in place and reconnected to the previous group's tail.
Why the other options are wrong
- AThe first group is reversed too.
- BThe short last group is not reversed.
- DThat reverses the whole list.