Singly Linked Lists
A singly linked list is a chain of nodes where each node holds a value and one pointer to the next node. Moving only forward makes insertion at a known spot O(1) but reaching a position, or a node's predecessor, an O(n) walk.
How a Singly Linked List Works
A singly linked list stores each value in its own node, together with one pointer, next, to the following node. The list itself is just a reference to the first node, head; the last node's next is null. Nodes can sit anywhere in memory, which is why the list can grow one node at a time without copying, unlike an array.
The single pointer decides the cost of all the singly linked list operations below. There is no indexing: reaching the kth node means following next k times from head, O(n). The tail is far away: appending walks the whole list unless a tail reference is kept as well; with one, append is O(1) and the list works as a queue. The predecessor is unknown: removing a node means changing the next of the node before it, and the only way to find that node is another walk from the head. That last weakness is what a doubly linked list fixes with a second pointer.
- Each node pays for a pointer (8 bytes on a 64-bit machine) plus allocator overhead, and scattered nodes are slower to scan than an array
- Traversal is
while current is not null: …; current = current.next; forgetting the last line loops forever
Insertion in a Singly Linked List
- At the head:
node.next = head, thenhead = node - After a known node p:
node.next = p.next, thenp.next = node - At the tail:
tail.next = node, thentail = node(O(1) only if a tail reference is kept)
Insertion is two pointer writes once you are at the right place, so it is O(1) at the head or after a node you already hold, and O(n) when you first have to walk to a position.
The order of the two writes matters. Setting p.next = node first overwrites the only reference to the rest of the list, and the next line, node.next = p.next, then makes the new node point at itself. Everything after p is lost. The rule behind every rewiring on this structure: save or copy the pointer you are about to overwrite before you overwrite it.
Head insertion needs no special case for an empty list: with head null, the new node's next becomes null and it becomes the only node.
- Inserting at position k costs k steps of walking plus O(1) for the link
- Head insertion reverses the input order: inserting 1, 2, 3 at the head gives 3 → 2 → 1
Deletion in a Singly Linked List
To delete a node, the node before it must skip over it: prev.next = prev.next.next. Then the removed node is freed (delete in C++, free in C, automatic in Python and Java). Finding prev is a walk from the head, so deleting by value is O(n) even though the unlinking itself is O(1).
Deleting the first node is the special case: it has no predecessor, so the code must change head instead. A dummy head node, a spare node placed before the real head, gives every real node a predecessor. The loop then treats the first node like any other, and the answer is dummy.next. The same trick simplifies building a new list, as in merge two sorted lists.
There is a well-known shortcut when you hold only the node to delete: copy the next node's value into it and unlink the next node instead. It is O(1), but it does not work on the last node, which has no successor to copy from; see delete node in a linked list.
- Before
prev.next.next, check thatprev.nextis not null - Practice: remove linked list elements is deletion by value with a dummy head
Terms, operations, and practical uses
Node structure
- NodeAn object containing a piece of data and a single pointer/reference to the next node in the sequence.
- Head PointerThe only required reference to manage the list, pointing to the very first node.
- Null ReferenceThe value stored in the final node's 'next' pointer, indicating the end of the list.
Algorithmic techniques
- Runner TechniqueUsing two pointers that traverse the list at different speeds (e.g., slow moves 1 step, fast moves 2 steps).
- Floyd's Cycle DetectionUsing the runner technique to detect infinite loops. If the fast pointer laps and equals the slow pointer, a cycle exists.
- Dummy NodeA fake head node used to simplify edge cases when inserting or deleting the very first real node.
Operations
- TraversalThe O(N) process of starting at the head and following pointers until null is reached.
- In-Place ReversalFlipping all 'next' pointers to face backward using three tracking variables (prev, current, next_temp).
- PredecessorThe node immediately before a target node. You must have a reference to the predecessor to delete a node in a singly linked list.
Code in Python, C++ and Java
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
head = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6))))))
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# even length: fast lands on None, so slow stops on the SECOND middle
print(f'Middle node is {slow.val} (second middle of an even-length list)')#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(NULL) {}
};
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next = new Node(6);
Node* slow = head;
Node* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
// even length: fast lands on NULL, so slow stops on the SECOND middle
cout << "Middle node is " << slow->val << " (second middle of an even-length list)\n";
}class Main {
static class Node {
int val;
Node next;
Node(int x) { val = x; }
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// even length: fast lands on null, so slow stops on the SECOND middle
System.out.println("Middle node is " + slow.val + " (second middle of an even-length list)");
}
}Step through it
Running on head → 1 → 2 → 4
Reversing a Singly Linked List
next = current.next: save the rest of the listcurrent.next = prev: turn this node's pointer backwardsprev = current: the reversed part now starts herecurrent = next: step into the saved rest
Reversal flips every next pointer to face the other way; no node moves. Three references are enough: prev starts at null, current at head, and next holds the rest of the list for one iteration. The four statements above run in that order until current is null.
The first statement is the one that cannot be skipped. As soon as current.next is set to prev, the old link to the rest of the list is gone, so it has to be saved first. At every moment prev heads the reversed part and current heads the untouched part; when current reaches null, prev is the new head, so return prev, not head.
It runs in O(n) time with O(1) extra space, and the empty list and the one-node list need no special handling. Practice: reverse linked list.
- Returning
headafter the loop returns the old first node, which is now the last - The recursive version is shorter but uses O(n) stack, which can overflow on long lists
Slow and Fast Pointers
Two references moving at different speeds answer position questions in one pass with O(1) memory. slow moves one node per round and fast moves two.
Finding the middle: loop while fast and fast.next are not null. When fast runs out, slow has covered half the distance and sits on the middle. On an even-length list this loop stops on the second of the two middles; testing fast.next and fast.next.next instead stops on the first. Practice: middle of the linked list.
Detecting a cycle (Floyd's algorithm): the same loop, checking whether slow and fast meet. If fast reaches null there is no cycle. If there is one, both pointers end up in it, and from then on fast gains exactly one node per round, so the gap shrinks to zero and they must meet. See linked list cycle and, for finding where the cycle starts, linked list cycle II.
The nth node from the end uses a fixed gap instead of two speeds: move one reference n steps ahead, then move both until the leader reaches the end. See remove nth node from end of list.
- Check
fastbeforefast.next, or the loop crashes on lists with an even number of nodes - More patterns on this list: linked lists