What is a linked list?#
A linked list is a chain of nodes. Each node holds a value and a pointer to the next node. The list is reached through a pointer to the first node, the head. The last node points to nullptr.
head
│
▼
[10 | •]──▶[20 | •]──▶[30 | •]──▶ NULL
data next
Unlike an array, the nodes can be anywhere in memory - they don't need one continuous block.
Linked list एक रेलगाड़ी की तरह है - हर डिब्बे (node) में सामान (data) है और एक कड़ी (pointer) जो अगले डिब्बे से जुड़ी है। नया डिब्बा जोड़ना आसान है (बस कड़ी बदलो), पर 5वें डिब्बे तक पहुंचने के लिए इंजन से एक-एक डिब्बा पार करना पड़ता है।
Building and traversing a list#
10 -> 20 -> 30 -> NULL
Inserting and deleting#
10 -> 20 -> 30 -> 40 -> NULL 10 -> 20 -> 40 -> NULL 20 -> 40 -> NULL
Keeping a separate tail pointer makes pushBack O(1) too. Always draw boxes and arrows on paper before writing pointer code - most linked-list bugs are lost pointers.
Every new needs a matching delete, otherwise memory leaks. And never use a node after deleting it. In modern C++ you often use std::list or smart pointers instead of raw new/delete.
Array vs linked list#
| Operation | Array / vector | Singly linked list |
|---|---|---|
| access k-th element | O(1) | O(k) |
| insert / delete at the front | O(n) | O(1) |
| insert / delete in the middle (position known) | O(n) | O(1) |
| insert at the end | O(1) amortised | O(1) with a tail pointer |
| search | O(n), O(log n) if sorted | O(n) |
| memory | compact, cache-friendly | extra pointer per node |
Variants: a doubly linked list has prev and next pointers (used for browser back/forward and LRU caches); a circular list links the last node back to the first (round-robin scheduling).
Classic interview patterns#
- Reverse a list - three pointers
prev,cur,nxt(exercise 1). - Find the middle - slow pointer 1 step, fast pointer 2 steps (exercise 2).
- Detect a cycle - if slow and fast ever meet, there is a loop (Floyd's algorithm).
- Merge two sorted lists - like the merge step of merge sort.
std::list and std::forward_list#
#include <list>
list<int> l = {20, 30};
l.push_front(10); // O(1)
l.push_back(40); // O(1)
l.remove(30); // removes all 30s
for (int x : l) cout << x << " "; // 10 20 40
Summary#
- A linked list is a chain of nodes (data + next pointer) starting from
head. - O(1) insert/delete at a known position; O(n) access by index.
- Reverse with
prev/cur/nxt; find the middle or a cycle with slow/fast pointers. - Use
std::listin real code; write your own to master pointers for interviews.