A linked list is a chain of nodes; each node holds data and a pointer to the next node. Size can grow at run time and insert/delete at the head is O(1), but there is no random access.
head → 10 → 20 → 30 → 40 → NULL
struct Node {
int data;
Node *next;
Node(int d) : data(d), next(nullptr) {}
};
void insertHead(Node *&head, int x) {
Node *n = new Node(x);
n->next = head;
head = n;
}
void print(Node *head) {
for (Node *cur = head; cur; cur = cur->next)
cout << cur->data << " ";
}
Node* reverse(Node *head) { // very common interview question
Node *prev = nullptr;
while (head) {
Node *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
- Singly — next pointer only.
- Doubly — next and prev pointers.
- Circular — last node points back to the first.
Q & A
-
Array vs linked list?Array: contiguous, O(1) index access, fixed size, costly insert/delete. Linked list: scattered nodes, O(n) access, dynamic size, O(1) insert/delete when you already have the node.
-
How to find the middle of a linked list?Slow and fast pointers: slow moves 1 step, fast moves 2 steps. When fast reaches the end, slow is at the middle.
-
How to detect a cycle?Floyd's algorithm: the same slow/fast pointers meet inside the loop if there is a cycle.