Module 5 · 15 min read · Free chapter
Linked lists
A linked list is a chain of nodes, each holding data and a pointer to the next. Insertion at the head is Θ(1), but search and reaching the k-th node take linear time. Reversal uses three pointers in Θ(n) time, and slow and fast pointers detect a cycle in Θ(1) space.
Start from zero: train coaches and their couplings
Stand on a railway platform and watch a goods train go by. The engine pulls the first coach, the first coach is coupled to the second, and so on to the last coach, which has nothing behind it. No coach knows its number in the train; it only knows which coach is coupled behind it.
Adding a coach in the middle is easy for the railway staff. They uncouple two coaches, put the new one in between and couple it on both sides, and nobody has to move the other coaches. But to reach the twentieth coach you must walk past the first nineteen.
A linked list works the same way. Each element, called a node, holds its data and a pointer to the next node, and the program remembers only where the first node is. The nodes may lie anywhere in memory, joined only by these pointers.
Compare this with an array, which is like seats numbered in one row of a cinema hall. You can go straight to seat 20, but squeezing in a new seat between 5 and 6 means shifting everyone after seat 5.
Why it matters. A list that grows and shrinks often, such as the songs in a playlist or the free blocks of memory, is easier to handle with links than with a fixed array. Linked lists also teach pointers, which GATE tests through short C programs every year.
The singly linked list in C
A node is a structure that holds the data and a pointer to a structure of the same type. The list itself is just a pointer called head to the first node, and an empty list has head = NULL. New nodes are made at run time with malloc.
struct node {
int data;
struct node *next;
};
struct node *push_front(struct node *head, int x) {
struct node *p = malloc(sizeof(struct node));
p->data = x;
p->next = head; /* new node points to old first node */
return p; /* new node is the new head */
}
Inserting at the front touches only two pointers, so it takes time whatever the length. Calling push_front with 30, then 20, then 10 builds the list 10 → 20 → 30 → NULL, because each new node goes in front of the old ones.
To traverse the list, start a pointer at the head and follow next until it becomes NULL, as in for (p = head; p != NULL; p = p->next). Printing, counting or searching all use this loop, so they take time. Reaching the -th node also needs steps, which is the price paid for flexible insertion.
Adding at the end needs a walk to the last node, which is . Many programs therefore keep a second pointer, tail, to the last node, and then appending becomes . But deleting the last node is still , because we must find the second-last node to set its next to NULL, and a singly linked node cannot look backwards.
Why it matters. These few costs, at the head, to search and to delete at the tail, are behind almost every comparison question. Memorise them with the reason, not as a list.
Insertion and deletion anywhere in the list
To insert a new node q after a node p, set q->next = p->next first and only then set p->next = q. The order matters. If you change p->next first, the rest of the list is lost, because no pointer remembers where it was.
Deletion needs the node before the one to be removed. So we walk with two pointers, prev one step behind cur, until cur reaches the key.
struct node *delete_key(struct node *head, int key) {
struct node *prev = NULL, *cur = head;
while (cur != NULL && cur->data != key) { prev = cur; cur = cur->next; }
if (cur == NULL) return head; /* key not found */
if (prev == NULL) head = cur->next; /* deleting the first node */
else prev->next = cur->next; /* skip over cur */
free(cur);
return head;
}
The search part costs , but the relinking itself is one assignment, which is . The special case of deleting the first node changes the head, so the function returns the new head. Forgetting free does not break the list, but it leaks memory that the program can never use again.
Worked example. In 10 → 20 → 30 → 40, delete 30. The loop stops with prev on 20 and cur on 30, so prev->next becomes the node 40 and node 30 is freed. The list is now 10 → 20 → 40, and only one pointer changed.
A neat trick deletes a node when you are given only a pointer to it and not to its predecessor. Copy the next node's data into it, then delete the next node instead. This works in , but it fails for the last node, which has no next node to copy from.
Why it matters. Pointer order is where most real bugs and most GATE options live. Two of the four choices in a typical question differ only in the order of two assignments, and only one order keeps the list intact.
Doubly and circular linked lists
A doubly linked list gives each node two pointers, prev to the node before and next to the node after. Now the list can be walked in both directions, and a node can be removed in given only a pointer to it, because it knows both neighbours. The price is one extra pointer per node and more pointer updates in every operation.
To insert node q after node p in a doubly linked list, four pointers change:
q->next = p->next;
q->prev = p;
if (p->next != NULL) p->next->prev = q;
p->next = q;
To delete a node d, its neighbours are joined around it: d->prev->next = d->next and d->next->prev = d->prev, with NULL checks at the two ends. So insertion between two nodes changes four pointers and deletion changes two. GATE sometimes asks exactly this count.
A circular linked list makes the last node point back to the first instead of to NULL. If the program keeps a pointer last to the final node, then last->next is the first node, so both ends are reachable in . Insertion at the front and at the end are then both , which is why a single last pointer is better than a head pointer here.
Traversal of a circular list cannot wait for NULL, because there is none. Instead it uses a do-while loop that stops on coming back to the starting node. Circular lists suit round-robin jobs, such as giving each process its time slice in turn or passing the turn around players in a game.
Why it matters. Browser history with Back and Forward, and the most-recently-used lists inside caches, need movement in both directions, so they use doubly linked lists. Round-robin schedulers use circular lists, and exam questions often ask which pointer to keep for insertion at both ends.
Reversing a list and detecting a cycle
Reversal asks you to turn every arrow around so that the last node becomes the head. Walk with three pointers: prev (already reversed part), cur (node being turned) and next (rest of the list, saved before it is lost).
struct node *reverse(struct node *head) {
struct node *prev = NULL, *cur = head, *next;
while (cur != NULL) {
next = cur->next; /* save the rest */
cur->next = prev; /* turn the arrow back */
prev = cur; /* move both one step on */
cur = next;
}
return prev; /* old last node is the new head */
}
For 1 → 2 → 3 → 4, the first pass makes 1 point to NULL, the second makes 2 point to 1, and so on, ending with 4 → 3 → 2 → 1 → NULL. Each node is touched once, so the time is and only three extra pointers are used, which is space. A recursive version is shorter to write, but it needs stack space for the n pending calls.
Detecting a cycle. A buggy program may make some node's next point back to an earlier node, so the list loops for ever. Floyd's method, also called the tortoise and the hare, moves a slow pointer one node at a time and a fast pointer two nodes at a time.
int has_cycle(struct node *head) {
struct node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return 1; /* they met inside a loop */
}
return 0; /* fast fell off the end */
}
If there is no cycle, fast reaches NULL. If there is a cycle, both pointers enter it, and inside the loop fast gains one node on slow at every step, so it must land on slow within one lap. The method takes time and only space, while the obvious method of storing every visited address needs space.
Two bonus results come from the same idea. When slow and fast meet, move one pointer back to the head and step both one node at a time, and they meet at the first node of the cycle. And when fast reaches the end of a cycle-free list, slow is standing on the middle node.
Why it matters. Reversal and cycle detection are the two most asked linked-list programs in interviews and written tests. They train you to keep track of several pointers at once, which is the core skill this topic tests.
Arrays versus linked lists, and stacks and queues on lists
Neither structure is always better. The table sets their costs side by side for a list of n elements.
| Operation | Array | Singly linked list |
|---|---|---|
| Read the -th element | ||
| Insert at the front | , elements shift | |
| Insert after a known position | ||
| Search in unsorted data | ||
| Search in sorted data | , binary search | |
| Extra memory | none | one pointer per node |
| Cache behaviour | good, cells are contiguous | poor, nodes are scattered |
The sorted row surprises many students. A linked list can be sorted, but binary search still fails on it, because jumping to the middle element takes steps along the chain. So a sorted linked list gives no faster search than an unsorted one.
A stack on a linked list. Push and pop both work at the head, which is , and the stack never overflows until the machine runs out of memory. Push is exactly push_front, and pop removes the head node and frees it.
A queue on a linked list. Keep two pointers, front at the first node and rear at the last. Enqueue adds a node after rear and moves rear, and dequeue removes the node at front, so both are . The direction matters, because removing at the rear of a singly linked list would need the second-last node and cost .
Why it matters. Choosing between an array and a list is a daily design decision, and IT officer papers ask for this comparison almost every year. The linked stack and queue also remove the fixed-size limit of the array versions.
Tracing GATE-style list code
GATE rarely asks you to write list code. It shows a short C function and asks what it does, so the skill is to trace it on a small list of four or five nodes. Here are two patterns that keep coming back.
Pattern 1: recursion before printing.
void show(struct node *p) {
if (p == NULL) return;
show(p->next);
printf("%d ", p->data);
}
On 1 → 2 → 3 the call show(1) first calls show(2), which calls show(3), which calls show(NULL) and returns. Only then do the printf lines run, in reverse order of the calls, so the output is 3 2 1. The function prints the list backwards in time, but it uses stack space; swapping the two middle lines would print it forwards.
Pattern 2: pointer surgery in a loop.
struct node *g(struct node *head) { /* list has at least 2 nodes */
struct node *q = NULL, *p = head;
while (p->next != NULL) { q = p; p = p->next; }
q->next = NULL;
p->next = head;
return p;
}
Trace it on 1 → 2 → 3 → 4 → 5. The loop stops with p on 5 and q on 4, the second-last node. Then 4 is made the end, 5 is pointed at the old head 1, and 5 is returned as the new head, so the result is 5 → 1 → 2 → 3 → 4.
So g moves the last node to the front, and it takes because of the walk to the second-last node. A good habit is to draw the boxes and arrows on rough paper and update them line by line. Guessing from the shape of the code is how most marks are lost.
Why it matters. One or two such questions appear in most GATE papers, and they are quick marks once tracing is a habit. The same tracing skill also helps you debug real C programs.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university-level tests ask about linked lists in four ways:
- They ask you to write C functions for insertion and deletion at the front, at the end and at a given position.
- They ask you to compare arrays and linked lists, or singly, doubly and circular lists, with costs and uses.
- They ask you to reverse a list, find its middle or detect a cycle, and to give the time and space used.
- They ask you to implement a stack or a queue using a linked list.
Practice questions (our own, not previous-year questions).
- Write a C function to insert a node at a given position in a singly linked list, handling the empty list and the first position. (10 marks)
- Compare arrays and linked lists for access, insertion, deletion, memory and cache use, with one application where each is better. (10 marks)
- Write a C function to reverse a singly linked list iteratively, trace it on a four-node list and state its complexity. (15 marks)
Answer plan for question 3.
- Start by defining the node structure in C with a data field and a next pointer.
- Explain the idea that every next pointer must be turned to point to the previous node.
- Introduce the three pointers prev, cur and next, and say what each one holds.
- Write the loop in which next is saved first,
cur->nextis set to prev, and both prev and cur move one step. - Trace the code on 1 → 2 → 3 → 4 with a small diagram after each pass.
- State that the time is because each node is visited once, and the extra space is .
- Close by noting that a recursive version also runs in but needs stack space.
Quick revision
- A node holds data and a next pointer, the head points to the first node, and the last node's next is NULL.
- Insertion at the head is , while search and reaching the -th node are and .
- A tail pointer makes appending , but deleting the last node of a singly linked list stays .
- When inserting, set the new node's next before changing the old node's next.
- A doubly linked list deletes a given node in , and insertion between two nodes changes four pointers.
- A circular list with a pointer to the last node gives insertion at both ends.
- Iterative reversal uses prev, cur and next, with time and space.
- Floyd's slow and fast pointers detect a cycle in time and space.
- Binary search gives no speed-up on a sorted linked list.
- A linked stack works at the head, and a linked queue enqueues at the rear and dequeues at the front.