DSA · Beginner · Pattern 8 of 11
Linked List
14 problems.
Your progress0%
- 1st Visit
- 0/14
- 2nd Visit
- 0/14
- Revise
- 0/14
About this pattern
A singly linked list stores nodes that point to their successor, so insertion and deletion are O(1) once you hold the right node, but reaching the k-th node takes O(k). Most problems reduce to a handful of pointer techniques: reversing links in place, a dummy head node that removes special cases at the front, slow and fast pointers that find the middle or detect a cycle, and two pointers kept a fixed gap apart.
Draw the pointers before coding and update next fields in an order that never loses the rest of the list. Solutions usually take O(n) time and O(1) extra space.
// Reverse a list in place.
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
while (head) {
ListNode* nxt = head->next; // save the rest first
head->next = prev;
prev = head;
head = nxt;
}
return prev;
}
// Middle node: fast moves two steps for each step of slow.
ListNode* slow = head; ListNode* fast = head;
while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }