Singly Linked List
A Singly Linked List is a linear data structure made up of nodes, where each node contains data and a reference (pointer) to the next node in the sequence. Unlike arrays, elements are not stored contiguously in memory.
Node Structure
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def delete(self, key):
current = self.head
prev = None
while current and current.data != key:
prev = current
current = current.next
if current is None:
return
if prev is None:
self.head = current.next
else:
prev.next = current.next
def traverse(self):
values = []
current = self.head
while current:
values.append(current.data)
current = current.next
return values
Complexity
| Operation | Time |
|---|---|
| Access by index | O(n) |
| Insert at head | O(1) |
| Insert at tail (no tail pointer) | O(n) |
| Delete | O(n) |
Advantages & Disadvantages
- Advantage: dynamic size, efficient insertions/deletions at the head.
- Disadvantage: no direct/random access; traversal is required to reach a given position, and extra memory is used for the next pointer.
Applications
- Implementing stacks and queues.
- Dynamic memory allocation systems.
- Building blocks for more advanced structures like hash maps (chaining) and graphs (adjacency lists).
Inserting at the Head and at a Given Position
Inserting at the head is the operation where a linked list beats an array, because nothing has to shift. Inserting at a position needs a walk to the node just before it.
def insert_at_head(self, data):
node = Node(data)
node.next = self.head # new node points to the old first node
self.head = node # head now points to the new node
def insert_at(self, index, data):
if index == 0:
return self.insert_at_head(data)
current = self.head
for _ in range(index - 1):
if current is None:
raise IndexError("index out of range")
current = current.next
if current is None:
raise IndexError("index out of range")
node = Node(data)
node.next = current.next # link the new node first...
current.next = node # ...then attach it
The order of the last two lines matters. If you set current.next = node first, you lose the reference to the rest of the list.
Reversing a List: Step-by-Step Trace
Reversal is one of the most asked linked list questions. You walk the list once and flip each pointer, using three variables.
def reverse(self):
prev = None
current = self.head
while current:
nxt = current.next # remember the rest of the list
current.next = prev # flip the pointer
prev = current # move prev forward
current = nxt # move current forward
self.head = prev
| Step | prev | current | Reversed part |
|---|---|---|---|
| Start | None | 1 | (empty) |
| After 1st loop | 1 | 2 | 1 → None |
| After 2nd loop | 2 | 3 | 2 → 1 → None |
| After 3rd loop | 3 | None | 3 → 2 → 1 → None |
It runs in linear time and uses constant extra memory.
Two-Pointer Techniques: Middle Node and Cycle Detection
Moving one pointer one step and another two steps at a time solves several problems in a single pass.
def middle(self):
slow = fast = self.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.data if slow else None
def has_cycle(self):
slow = fast = self.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
When the fast pointer reaches the end, the slow one is in the middle. If the list accidentally loops back on itself, the fast pointer eventually laps the slow one and they meet. This is known as Floyd's cycle detection.
Both pointers start at the head, and the loop condition checks fast and fast.next so the fast pointer never jumps past the end. For a list with an even number of nodes, this version returns the second of the two middle nodes. Interviewers sometimes ask for the first one instead; starting fast at head.next gives that result. Being able to explain such small changes shows you understand the technique rather than having memorised it.
Bugs to Avoid and a Revision List
- Not handling an empty list (
headisNone) before readinghead.next. - Forgetting to update
headafter deleting or reversing. - Losing the rest of the list by overwriting
nextbefore saving it. - Using a linked list for heavy index-based access, where an array or Python list is faster.
Practise these until they are automatic
- Insert at head, tail and a position.
- Delete by value and by position.
- Reverse iteratively, then try it recursively.
- Find the middle and detect a cycle with two pointers.
- Merge two sorted lists into one.