LeetCode Linked List Question Summary
Xiahua Liu November 09, 2024 #LeetCode #C++ #AlgorithmAfter solving around 20 LeetCode linked-list problems, here is a concise summary of patterns and templates.
Type Definition
The standard singly linked list definition used by LeetCode is:
;
Linked List Traversal
Unlike arrays, you cannot access random elements in a linked list. You must traverse it sequentially. The direction of processing determines the logic.
1. Forward Traversal (Pre-Order)
We process the current node before moving to the next.
Iterative style (most common):
for
If you need to manipulate links (delete a node or reverse a link), keep track of the previous node:
ListNode* prev = nullptr;
for
Recursive style: performing action before the recursive call:
void
If you need the prev pointer in recursion, pass it as an argument:
void
// Initial call
// traverse(nullptr, head);
2. Backward Traversal (Post-Order)
Process nodes in reverse order (tail → head). Use a stack or recursion.
Iterative (using stack) — uses O(N) extra space:
stack<ListNode*> st;
for st.;
while
Recursive (post-order): perform action after the recursive call returns:
void
Example: Reverse Linked List (LeetCode 206)
Several common methods to reverse a singly linked list.
Method 1 — Iterative (forward logic):
ListNode*
Method 2 — Recursive (tail recursion / forward logic):
ListNode*
ListNode*
Method 3 — Recursive (standard post-order):
ListNode*
Important Patterns
1. Dummy Node
When modifying list structure (insert/delete/merge), the head may change. Use a dummy node to simplify edge cases:
ListNode* dummy = new ;
dummy->next = head;
ListNode* cur = dummy;
// ... perform operations using cur ...
return dummy->next; // Actual head
2. Fast & Slow Pointers (Tortoise & Hare)
Useful for detecting cycles and finding the middle of the list. Slow moves 1 step; Fast moves 2 steps.
ListNode* slow = head;
ListNode* fast = head;
while
// If no cycle, 'slow' is at the middle when loop ends