Sub topic 4
Singly linked lists: nodes, traversal, insertion, deletion
This chapter assumes you know arrays and index arithmetic, can read basic Python, understand object references (pointers), and know introductory Big-O notation. It builds the singly linked list from scratch and counts the cost of each operation, which is the style GATE questions use.
The node and the list
A singly linked list is a sequence of nodes. Each node stores a data value and a reference to the next node. The last node's reference is None (null in C and Java). The list itself is usually represented by one variable, head, which references the first node. An empty list has head = None.
Unlike an array, the nodes are not stored in contiguous memory. Each node can live anywhere, and the next references connect them. This has three consequences:
- There is no index arithmetic. To reach the k-th node you must follow k references from the head.
- Inserting or deleting needs no shifting of elements. It only changes a few references.
- Each node pays extra memory for its reference, and nodes are allocated one at a time.
Here is a node class and a minimal list class. The code runs as shown.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def __iter__(self):
cur = self.head
while cur is not None:
yield cur.data
cur = cur.next
def __repr__(self):
return " -> ".join(str(x) for x in self) + " -> None"Traversal and search
Traversal visits every node once. You start at head and move with cur = cur.next until cur is None.
def length(head):
count = 0
cur = head
while cur is not None:
count += 1
cur = cur.next
return count
def search(head, key):
cur = head
while cur is not None:
if cur.data == key:
return cur
cur = cur.next
return NoneBoth functions take O(n) time in the worst case and O(1) extra space. Search is O(n) even if the list is sorted, because there is no way to jump to the middle. This is the main difference from binary search on a sorted array.
Accessing the k-th node (0-based) takes k steps, so it is O(k), and O(n) in the worst case. In an array it is O(1).
Insertion
Insertion has three cases, with different costs.
Insert at the head
Create a new node, point its next at the old head, then move head to the new node. The order matters. If you move head first, you lose the rest of the list.
def insert_front(head, x):
return Node(x, head)The function returns the new head, so the caller writes head = insert_front(head, 5). This takes O(1) time.
Insert after a given node
If you already hold a reference to node p, you can insert after it in O(1) time.
def insert_after(p, x):
p.next = Node(x, p.next)The right-hand side Node(x, p.next) is evaluated first, so the new node captures the old successor before p.next is overwritten. In C you must write the two assignments in this order explicitly: new->next = p->next; and then p->next = new;. Swapping them makes the new node point to itself and loses the tail.
Insert at the tail or at a position
Without a tail reference, you must walk to the last node first, so insertion at the end is O(n). If the list also keeps a tail reference, it is O(1).
def insert_at(head, index, x):
"""Insert x so it ends up at position index (0-based). Returns the new head."""
if index == 0:
return Node(x, head)
cur = head
for _ in range(index - 1):
if cur is None:
raise IndexError("index out of range")
cur = cur.next
if cur is None:
raise IndexError("index out of range")
cur.next = Node(x, cur.next)
return headFinding the predecessor takes index - 1 steps, so the total cost is O(index). The insertion itself is O(1). The cost is in locating the position, not in changing links.
Deletion
To delete a node you must change the next of its predecessor, so deletion is also about finding the predecessor.
Delete the head
def delete_front(head):
if head is None:
raise IndexError("delete from empty list")
return head.nextThis is O(1). In C you must also free the removed node, and you must save it in a temporary variable before moving head.
Delete by key
def delete_key(head, key):
if head is None:
return None
if head.data == key:
return head.next
prev = head
while prev.next is not None and prev.next.data != key:
prev = prev.next
if prev.next is not None:
prev.next = prev.next.next
return headThe loop stops with prev at the node before the target. The assignment prev.next = prev.next.next skips the target. The head is handled separately because it has no predecessor. This takes O(n) time in the worst case.
Delete a given node when you only hold a pointer to it
A classic exam trick: you hold a reference p to a node, but not to its predecessor. If p is not the last node, copy the successor's data into p and unlink the successor.
def delete_node_given_pointer(p):
if p is None or p.next is None:
raise ValueError("cannot delete the last node this way")
p.data = p.next.data
p.next = p.next.nextThis runs in O(1). It fails for the last node, because there is no successor to copy from. It also changes which node object holds which value, which breaks any other reference that expected p to keep its old data.
Cost table
| Operation | Singly linked list (head only) | Array |
|---|---|---|
| Access k-th element | O(k), worst O(n) | O(1) |
| Search (unsorted) | O(n) | O(n) |
| Insert at front | O(1) | O(n) |
| Insert at end | O(n), or O(1) with a tail pointer | O(1) amortized if space remains |
| Insert after a known node | O(1) | O(n) |
| Delete front | O(1) | O(n) |
| Delete a known node (pointer to it only) | O(1) by copying, except the last node | O(n) |
| Delete by key | O(n) | O(n) |
| Extra memory | One reference per node | None per element |
Edge cases and common errors
- Empty list. Always check
head is Nonebefore readinghead.nextorhead.data. This is the most common cause of a null-dereference. - Single-node list. Deleting the only node must set
headtoNone. A tail pointer, if kept, must be updated too. - Deleting the tail. If you keep a
tailreference, a singly linked list cannot find the new tail in O(1). You must walk from the head, so delete at the end is O(n) even with a tail pointer. - Wrong link order. In insertion, set the new node's
nextfirst. In deletion, save what you need before overwriting links. - Losing the head. Never advance
headitself while traversing, unless you have saved it. Use a separate variable such ascur. - Passing head by value. In C, a function that changes the head needs a pointer to the head (
Node **head) or must return the new head. In Python, the same problem appears if you writehead = ...inside a function and expect the caller to see it.
Counting operations in exam questions
GATE questions often ask for the number of pointer changes or the time for a sequence of operations. Use this approach:
- Identify what you hold: only
head,headandtail, or a pointer to a specific node. - Count the steps needed to find the predecessor. This is usually the dominant cost.
- Add the constant number of link changes for the actual insertion or deletion. Inserting after a known node changes two links, and deleting after a known node changes one.
For example, a queue built on a singly linked list with only a head pointer needs O(n) to enqueue at the tail. Adding a tail pointer makes enqueue at the tail and dequeue from the head both O(1). Pushing and popping at the head is O(1), so a stack on a singly linked list should use the head as its top.
Exercise
A singly linked list has only a head pointer and holds n nodes. What is the worst-case time to (a) insert a node at the front, (b) insert a node at the end, (c) delete the last node? Which of these improves to O(1) if you add a tail pointer?
Show answer
(a) O(1). (b) O(n), because you must walk to the last node. (c) O(n), because you must find the second-to-last node to set its next to None. Adding a tail pointer makes only (b) O(1). Deleting the last node stays O(n) because the new tail can only be found by walking from the head.
Exercise
You are given a pointer p to a node in the middle of a singly linked list, with no access to head. Describe how to delete that node in O(1) time and state one case where it fails.
Show answer
Copy p.next.data into p.data, then set p.next = p.next.next. This removes the successor's node while keeping p's position. It fails when p is the last node, because there is no successor to copy from. It also fails to preserve identity, so any other reference to the successor node becomes invalid.