</>

🔗 Linked List Problem Solving Template 🚀


What it is: A linear data structure where elements (nodes) are not stored at contiguous memory locations. Each node points to the next node in the sequence.

Core Benefit: Efficient insertions and deletions at any point in the list, as it only requires updating a few pointers.


✨ Typical Patterns & Techniques

Pattern/Technique Purpose & When to Use Code Example (Conceptual)
Dummy Head Node Simplifies list construction and head modifications by providing a consistent starting point, avoiding special-casing the first node. Stack Allocation: ListNode dummy(0, head); (no need to delete)
Heap Allocation: ListNode* dummy = new ListNode(0); (need to delete)
Two Pointers (Slow/Fast) Detect cycles, find middle, or locate N-th node from end. Slow moves 1x, Fast moves 2x. For N-th from end, one starts N steps ahead. slow = head, fast = head;
while(fast && fast->next) { slow=slow->next; fast=fast->next->next; }
Iterative Traversal The most fundamental way to walk through a list node by node. ListNode* cur = head;
while (cur) { /* ... */ cur = cur->next; }
Reversing Iteratively A common sub-problem. Changes A -> B -> C to A <- B <- C. Requires tracking previous, current, and next nodes. prev=nullptr, cur=head;
while(cur) { temp=cur->next; cur->next=prev; prev=cur; cur=temp; }

💡 General Steps for Linked List Problems


🧠 Typical ListNode Definition

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};