Chapter 4: Linked Lists
Introduction
Learning Outcomes
Define a self-referential struct, check the result of malloc, release with free.
Insert at the front, back, middle and in order, in the right sequence, without losing a link.
Delete nodes without memory leaks or dangling pointers.
Write reversal, merging, finding the middle and Floyd’s cycle detection with O(1) extra space.
Choose circular, doubly linked and header-node lists to fit the task.
Reuse nodes with an available space list.
Why Lists?
When arrays fall short: links instead of shifting
We insert 10 after 8. The array must shift later elements to make room; the list only changes links.
Array: 20 moved one place right (move 1).
Array: 12 moved one place right (move 2). An n-element array needs n moves in the worst case: O(n).
Array: 10 written into the freed cell.
List: a new node is allocated and temp->link points to 12. No element moved.
List: 8->link = temp. If the position is known, just two links: O(1).
Why Lists?
Nodes need not sit next to each other in memory
The link field holds the address of the next node; NULL in the last node.
The address of node i cannot be computed; follow the links from the head: O(i).
On old x86 an address had two parts (segment + offset): segmented memory. Today it is a flat address space.
Why Lists?
A pointer refresher
int x = 5; int *p = &x; // p holds the address of x *p = 7; // write through p: x == 7 node_ptr q = NULL; // no node yet q = malloc(sizeof *q); if (q != NULL) { q->data = 3; // (*q).data = 3 q->link = NULL; } free(q); // released; q now dangles q = NULL;
& and *&x: the address of x · *p: the object p points to.
->q->data is the same as (*q).data; the parentheses are needed for precedence.
A pointer that points nowhere; it represents the empty list.
Why Lists?
Allocating a node: malloc, the check, free
node_ptr new_node(int x) { node_ptr p = malloc(sizeof *p); if (p == NULL) { fprintf(stderr, "No memory, no memoryyy...\n"); exit(1); } p->data = x; p->link = NULL; return p; }
sizeof *p and NULLRight size without repeating the type. Out of memory, malloc returns NULL; sample message: No memory, no memoryyy...
One free per malloc; double free or use after free is undefined behavior.
Traversal pointers (p = p->link) point to existing nodes; no malloc.
Singly Linked Lists
A node: a self-referential struct
typedef struct node *node_ptr; // pointer type first struct node { int data; // data field node_ptr link; // address of the next node }; node_ptr list = NULL; // empty list
The structure contains a pointer to its own type; declaring a pointer to an incomplete type is allowed.
The pointer type can be called list_pointer, node_ptr or similar; here node_ptr.
typedef struct list { … }; without a name for the typedef. Either drop the typedef or put a type name at the end.Singly Linked Lists · Step by step
Traversing a list: p = p->link
print_list(list): the pointer is passed by value; advancing p does not change list in main.
p is at the first node: print 7.
p = p->link: the second node.
Print 2.
The third node.
Print 9.
p == NULL: the loop ends.
End of line. n rounds for n nodes: O(n).
void print_list(node_ptr p) { for (; p != NULL; p = p->link) printf("%d ", p->data); printf("\n"); }
The length is counted the same way: for (; p != NULL; p = p->link) n++;
Singly Linked Lists
Inserting at the front, and passing by address
bool insert_front(node_ptr *head, int x) { node_ptr temp = malloc(sizeof *temp); if (temp == NULL) return false; temp->data = x; temp->link = *head; *head = temp; return true; } node_ptr list = NULL; insert_front(&list, 2); // 2 insert_front(&list, 7); // 7 -> 2
node_ptr *head?The head will change. Passed by value, only a local copy would change and list in main would stay stale.
Writing *head = temp first would link the node to itself and lose the rest of the list. Cost O(1).
Singly Linked Lists · Run the code step by step
Code Trace: insert_front(&list, 5)
The call: insert_front(&list, 5). head is the address of the variable list in main; the list is 7 → 2.
malloc allocated a node on the heap. Its fields still hold garbage.
temp != NULL: allocation succeeded, go on. (Otherwise it would return false with the list intact.)
Fill the data field: temp->data = 5.
First keep the old head: temp->link = *head → the new node points to 7. list still points to 7.
Then change the head: *head = temp. Thanks to passing by address, list in main is updated.
The list is now 5 → 7 → 2. A constant amount of work, independent of the length: O(1).
bool insert_front(node_ptr *head, int x) { node_ptr temp = malloc(sizeof *temp); if (temp == NULL) return false; // no memory temp->data = x; temp->link = *head; // first keep old head *head = temp; // then move the head return true; }
Singly Linked Lists · Step by step
Inserting at the back: finding the last node is O(n)
The new node (5) is ready; link = NULL since it will be last.
The list is not empty: p starts at the head.
It advances until p->link == NULL: the last node is 6. This walk is O(n).
p->link = temp. If we always append, keeping a tail pointer makes it O(1) (that is how a linked queue works).
bool insert_back(node_ptr *head, int x) { node_ptr p, temp = malloc(sizeof *temp); if (temp == NULL) return false; temp->data = x; temp->link = NULL; // the new last node if (*head == NULL) { *head = temp; return true; } for (p = *head; p->link != NULL; p = p->link) ; // find the last node p->link = temp; return true; }
Singly Linked Lists · Step by step
Inserting in the middle: keep the successor first, then link
12 → 7 → 25; prev = node(7). Insert 9 after 7.
new_node(9): node allocated, link = NULL.
p->link = prev->link: 25’s address is copied into the new node; nothing lost.
prev->link = p: 12 → 7 → 9 → 25. O(1) when the node is known.
// adds a node holding x after prev node_ptr insert_after(node_ptr prev, int x) { node_ptr p = new_node(x); // malloc + check if (prev != NULL) { // middle or end p->link = prev->link; prev->link = p; } // else alone return p; }
Generalizes new_term(expon, coef, prev) from polynomial multiplication.
Singly Linked Lists · Run the code step by step
Code Trace: insert_sorted() — insert 7
We insert 7 into the sorted list 2 → 5 → 9. The new node (from malloc) is ready; temp->link is not linked yet.
p starts at the head; prev will trail one step behind p (NULL for now).
Condition: 2 < 7 → true. We must go further.
prev = p → node(2).
p = p->link → &node(5).
Condition: 5 < 7 → true. We must go further.
prev = p → node(5).
p = p->link → &node(9).
Condition: 9 < 7 → false. The insertion point is found: between prev and p.
First link the new node to p: temp->link = p (so the address of 9 is not lost).
prev != NULL: we insert in the middle, not at the front; the head stays.
prev->link = temp: 5 now points to 7. The list is 2 → 5 → 7 → 9.
void insert_sorted(node_ptr *head, node_ptr temp) { node_ptr prev = NULL, p = *head; while (p != NULL && p->data < temp->data) { prev = p; p = p->link; } temp->link = p; if (prev == NULL) *head = temp; // at the front else prev->link = temp; // middle/end }
Singly Linked Lists · Step by step
Deletion: we need the node before the victim
To delete a node from a singly linked list we need the node before it: here 3.
victim = prev->link: keep the address, or we could not free it.
prev->link = victim->link: 3 now points to 2, and 8 is out of the chain.
free(victim): node 8 is released. Deleting the head has no predecessor → a special case (or a header node).
// deletes the node after prev from the list // and from memory void delete_next(node_ptr prev) { node_ptr victim = prev->link; // keep the address if (victim == NULL) return; // nothing to delete prev->link = victim->link; // fix the link free(victim); // free the leftover }
Singly Linked Lists · Run the code step by step
Code Trace: delete_key(&list, 1)
The list is 3 → 8 → 1 → 6; we delete x = 1. p starts at the head, prev = NULL.
Condition 3 != 1 → true. Keep searching.
prev = p → node(3).
p = p->link → &node(8).
Condition 8 != 1 → true. Keep searching.
prev = p → node(8).
p = p->link → &node(1).
Condition 1 != 1 → false. The node to delete is found; prev is one step behind.
p != NULL: x is in the list, go on to delete it.
prev != NULL: it is not the head; *head will not change.
prev->link = p->link: 8 now points to 6; 1 is bypassed.
free(p): the node goes back to memory. Forgetting this causes a memory leak.
The list is 3 → 8 → 6. Search O(n), relinking O(1): O(n) in total.
bool delete_key(node_ptr *head, int x) { node_ptr prev = NULL, p = *head; while (p != NULL && p->data != x) { prev = p; p = p->link; } if (p == NULL) return false; // x absent if (prev == NULL) *head = p->link; // the head else prev->link = p->link; // bypass free(p); return true; }
Singly Linked Lists
Searching and reaching the i-th node
node_ptr search(node_ptr p, int x) { while (p != NULL && p->data != x) p = p->link; return p; // NULL if not found } node_ptr nth(node_ptr p, int i) { // 0-based while (p != NULL && i-- > 0) p = p->link; return p; // NULL if i >= length }
p != NULL && p->data != x: in the reverse order we would look inside NULL at the end of the list.
Search is O(n) in the worst case, nth(p, i) is O(i). Not O(1) like a[i] in an array.
We can stop as soon as p->data > x; still O(n) worst case. Binary search is useless on a linked list.
Singly Linked Lists
Exam question: which one is right?
list in the caller?void free_list( list_ptr *list ){ node_ptr p = *list; if( *list ){ p = *list->link; free(*list); free_list(&p); }}
void free_list( list_ptr *list ){ node_ptr p = *list; if( p ){ *list = p->link; free(p); free_list(list); }}
Solution
The left one recurses with the address of the local p: list in the caller never becomes NULL and points to a freed node (a dangling pointer). Also *list->link = *(list->link) does not compile; (*list)->link was meant. The right one advances *list and continues with the same address.
Singly Linked Lists · Run the code step by step
Code Trace: free_list(&lst)
Call 1: p = *list → &node(4).
p != NULL: there is a node to free.
*list = p->link: lst in main is now &node(9).
free(p): node(4) is released; p is now a dangling pointer and must not be used.
Recursive call with the same list address: free the rest of the list.
Call 2: p = *list → &node(9).
p != NULL: there is a node to free.
*list = p->link: lst in main is now NULL.
free(p): node(9) is released; p is now a dangling pointer and must not be used.
Recursive call with the same list address: free the rest of the list.
Call 3: p = *list → NULL.
p == NULL: the list is done; the call returns without doing anything. Base case.
Back in call 2; nothing left to do.
Back in call 1; nothing left to do.
Every node is freed and lst == NULL in main: no dangling pointer is left.
void free_list(node_ptr *list) { node_ptr p = *list; if (p) { *list = p->link; // first advance the head free(p); // then free the old head free_list(list); // same address again } }
Singly Linked Lists
The same job, iteratively
void clear_list(node_ptr *list) { while (*list != NULL) { node_ptr p = *list; *list = p->link; // advance first free(p); // then free } }
One call frame per node: with n = 10⁶ nodes the stack may overflow.
O(n) time, O(1) extra space; *list ends up NULL.
Take the next address before free; never read the link of a freed node.
Classic Routines
Question: reverse the links (invert)
invert that reverses the link fields of the list pointed to by list.Midway: the part up to r and q is reversed, the part from p on still points the old way.
r trails, q is in the middle, p leads; each round reverses one link.
No new nodes, no copies: O(n) time, O(1) extra space.
That is why the list is passed by address as node_ptr *list.
Classic Routines · Run the code step by step
Code Trace: invert(&list)
Three pointers: p leads (the head), q is in the middle (NULL), r trails (no value yet).
p != NULL: a round begins.
Round 1: r = q → NULL.
q = p → &node(10): the node whose link is reversed this round.
p = p->link → &node(20). We advance first so the rest of the list is not lost.
q->link = r: node(10) now points to NULL.
p != NULL: a round begins.
Round 2: r = q → &node(10).
q = p → &node(20): the node whose link is reversed this round.
p = p->link → &node(30). We advance first so the rest of the list is not lost.
q->link = r: node(20) now points to node(10).
p != NULL: a round begins.
Round 3: r = q → &node(20).
q = p → &node(30): the node whose link is reversed this round.
p = p->link → NULL. We advance first so the rest of the list is not lost.
q->link = r: node(30) now points to node(20).
p == NULL: the loop ends; q is at the last node.
*list = q: the old last node is the new head. 30 → 20 → 10; O(n) time, O(1) extra space, no malloc.
void invert(node_ptr *list) { node_ptr r, p = *list, q = NULL; while (p) { r = q; // r trails q q = p; // q trails p p = p->link; // advance p q->link = r; // reverse the link } *list = q; // last node is the head }
Classic Routines · Step by step
Concatenating two lists end to end
L1 = 1 → 4, L2 = 6 → 9. Neither is empty.
p walks from the head of L1.
p->link == NULL: the last node of L1 is found. Cost O(|L1|).
p->link = L2: 1 → 4 → 6 → 9. No copies. With a last pointer on a circular list this is O(1).
// links L2 to the end of L1, returns the head node_ptr concat(node_ptr L1, node_ptr L2) { node_ptr p; if (L1 == NULL) return L2; if (L2 != NULL) { for (p = L1; p->link != NULL; p = p->link) ; // last node of L1 p->link = L2; } return L1; }
Classic Routines · Step by step
The middle node: slow and fast pointers
Both start at the head.
slow takes 1 step, fast takes 2.
fast is at the last node (fast->link == NULL): the loop ends and slow = 3 is in the middle.
return slow: one pass, O(n) time, O(1) extra space.
node_ptr middle(node_ptr head) {
node_ptr slow = head, fast = head;
while (fast != NULL && fast->link != NULL) {
slow = slow->link; // 1 step
fast = fast->link->link; // 2 steps
}
return slow;
}For even length (1 → 2 → 3 → 4) the second middle (3) is returned; for the first middle use the condition fast->link->link != NULL.
Classic Routines
Floyd’s cycle-detection algorithm (tortoise and hare)
A faulty link (last->link = some_middle_node) puts the list in a cycle; print_list never ends.
slow takes 1 step, fast takes 2. Without a cycle fast reaches NULL; with one, once both are in the cycle the gap shrinks by 1 each round → they must meet.
O(n) time, O(1) extra space. Keeping visited nodes in a set also works but needs O(n) space.
After they meet, move one pointer back to the head and advance both one step at a time: the node where they meet again is the cycle’s entry.
Floyd (1967); Knuth, TAOCP Vol. 2, Exercise 3.1-6.
Classic Routines · Run the code step by step
Code Trace: has_cycle() — tortoise and hare
The tortoise (slow) and the hare (fast) start together at the head. The list has a cycle 5 → 3.
fast and its successor are not NULL: keep running.
Round 1: the tortoise takes 1 step → node(2).
The hare takes 2 steps → node(3).
Not on the same node; continue.
fast and its successor are not NULL: keep running.
Round 2: the tortoise takes 1 step → node(3).
The hare takes 2 steps → node(5).
Not on the same node; continue.
fast and its successor are not NULL: keep running.
Round 3: the tortoise takes 1 step → node(4).
The hare takes 2 steps → node(4).
They meet! The hare lapped the cycle and caught the tortoise → there is a cycle, true.
bool has_cycle(node_ptr head) { node_ptr slow = head, fast = head; while (fast != NULL && fast->link != NULL) { slow = slow->link; // 1 step fast = fast->link->link; // 2 steps if (slow == fast) return true; } return false; }
Circular and Doubly Linked
A circular list: the last node points to the first
int c_length(node_ptr last) { int n = 0; node_ptr p = last; if (last == NULL) return 0; // empty list do { n++; p = p->link; } while (p != last); // full circle return n; }
last?last->link is the first node: inserting at both the front and the back is O(1).
A traversal ends by coming back around, not at p == NULL; hence do-while.
Circular and Doubly Linked · Step by step
Inserting at the front and back of a circular list
3 → 5 → 8 → (3), last = 8. We insert the new node 1.
temp->link = last->link: the new node points to the old first node (3).
last->link = temp: 8 now points to 1. Front insertion done: 1 → 3 → 5 → 8.
Back insertion = front insertion + *last = temp: last is now 1; order 3 → 5 → 8 → 1. Both are O(1).
void c_insert_front(node_ptr *last, node_ptr temp) { if (*last == NULL) { // empty list *last = temp; temp->link = temp; // points to itself } else { temp->link = (*last)->link; // old first node (*last)->link = temp; } }
Back insertion: c_insert_front(last, temp); *last = temp; — front and back insertion are the same link operation; only the last pointer differs.
Circular and Doubly Linked
The header (sentinel) node
// sorted insert in a header list: no special case void h_insert_sorted(node_ptr header, node_ptr temp) { node_ptr prev = header; // never NULL while (prev->link != NULL && prev->link->data < temp->data) prev = prev->link; temp->link = prev->link; prev->link = temp; }
A node at the front that carries no data and is never deleted. Empty list = just the header.
Every real node has a predecessor: the *head and if (prev == NULL) special cases disappear.
Circular and Doubly Linked
The doubly linked list
typedef struct dnode *dnode_ptr; struct dnode { dnode_ptr llink; // previous int data; dnode_ptr rlink; // next }; // invariant: p == p->llink->rlink == p->rlink->llink
Pros
- Traversal in both directions
- O(1) deletion of a known node
- O(1) insertion before a node
Cons
- 2 pointers per node
- 4 links per operation
- Easier to get a link wrong
Circular and Doubly Linked · Run the code step by step
Code Trace: dinsert(p, temp)
A circular doubly linked list with a header node: H ⇄ 4 ⇄ 8 ⇄ H. We insert 6 to the right of 4.
temp->llink = p: the new node’s left link points to 4.
temp->rlink = p->rlink: its right link points to 8. The list has not changed yet; only the new node is prepared.
p->rlink->llink = temp: 8’s left link is now 6. (Since it relies on p->rlink still being 8, this line could not come after the 4th assignment, p->rlink = temp.)
p->rlink = temp: the last link. Four links updated, no special case: O(1).
Result: H ⇄ 4 ⇄ 6 ⇄ 8 ⇄ H. Thanks to the header node, the same code works on an empty list and at the end.
// inserts temp to the right of node p void dinsert(dnode_ptr p, dnode_ptr temp) { temp->llink = p; temp->rlink = p->rlink; p->rlink->llink = temp; p->rlink = temp; }
Circular and Doubly Linked · Step by step
Deleting from a doubly linked list: no search for the predecessor
H ⇄ 4 ⇄ 6 ⇄ 8 ⇄ H; p = node(6). Its predecessor is already at hand as p->llink.
p->llink->rlink = p->rlink: 4’s right is now 8.
p->rlink->llink = p->llink: 8’s left is now 4.
free(p). No search: O(1). Thanks to the header, the first/last node needs no separate code.
void ddelete(dnode_ptr header, dnode_ptr p) { if (p == header) { // never delete header fprintf(stderr, "Cannot delete header\n"); return; } p->llink->rlink = p->rlink; p->rlink->llink = p->llink; free(p); }
Memory Management
The available space list
node_ptr avail = NULL; // available nodes node_ptr get_node(void) { node_ptr p; if (avail != NULL) { // take from the list p = avail; avail = avail->link; } else { // else ask the system p = malloc(sizeof *p); if (p == NULL) exit(1); } return p; } void ret_node(node_ptr p) { // instead of free p->link = avail; avail = p; }
Deleted nodes go onto the avail chain instead of to free; new nodes are taken from there first.
Programs that insert and delete a lot make fewer malloc/free calls; getting/returning a node is O(1).
Nodes on avail are not returned to the heap until the program ends; useful when there is a single node type.
Memory Management
get_node and ret_node step by step
The avail chain holds two free nodes; on the right, node(9) is in use.
get_node(): avail is not empty → p = avail. No malloc call.
avail = avail->link: the head of the chain moves on; p now belongs to the caller.
ret_node(old): old->link = avail.
avail = old: the node is ready to be reused. Both are O(1), like push/pop on a linked stack.
avail is a stack: get_node = pop, ret_node = push.Memory Management · Step by step
Returning a circular list in one move (Horowitz: cerase)
3 → 5 → 8 → (3), last = 8; avail holds one node. first = last->link = 3.
last->link = avail: the ring is opened and its end joined to the avail chain.
avail = first: the whole list now sits in front of avail.
*last = NULL. O(1) whatever the length; for a plain singly linked list, finding the end would take O(n).
// return a circular list to avail in O(1) void cerase(node_ptr *last) { node_ptr first; if (*last != NULL) { first = (*last)->link; // first node (*last)->link = avail; // open the ring avail = first; *last = NULL; } }
Lab · C code step by step
Lab: Singly Linked List
Wrap-Up
Complexity summary
| Operation | Array | Singly linked (head) | Circular (last) | Doubly linked (header) |
|---|---|---|---|---|
| Access the i-th element | O(1) | O(i) | O(i) | O(i) |
| Insert at front | O(n) | O(1) | O(1) | O(1) |
| Insert at back | O(1)* | O(n) | O(1) | O(1) |
| Insert after a known node | O(n) | O(1) | O(1) | O(1) |
| Delete a known node | O(n) | O(n)† | O(n)† | O(1) |
| Search by value | O(n) | O(n) | O(n) | O(n) |
| Concatenate | O(n+m) | O(n) | O(1) | O(1) |
| Extra space per node | — | 1 pointer | 1 pointer | 2 pointers |
* needs resizing when full · † a traversal to find the predecessor; O(1) if it is known. Floyd, middle node, reversal: O(n) time, O(1) extra space.
Wrap-Up
Common mistakes
p->link = temp first and the rest of the list is lost.node_ptr head); the list in main is not updated.malloc; forgetting free (a leak) or calling it twice.link of a freed node; save the successor first, then free.p != NULL: the loop never ends.Wrap-Up
Exercises
- Merge two sorted lists into one sorted list without allocating nodes.
- Find the k-th node from the end of a list in a single pass.
- Delete the duplicates from a sorted list; return the deleted nodes with
ret_node. - Write
invertrecursively. What is the extra space? - After Floyd finds a cycle, compute the length of the cycle.
Answers / hints
- Link the smaller one to the result and advance; at the end append the list that remains, not the one that ran out. O(n+m).
- Move the fast pointer k steps ahead, then walk both together.
- While a neighbor is equal,
delete_next(p); O(n). - Reverse the rest, then
p->link->link = p; p->link = NULL; O(n) because of the stack. - Count from the meeting node until you return to it.
Wrap-Up
Chapter summary
List elements are scattered; the order is built with link fields. Empty list = NULL.
Save first, link next, release (free) last. Pass by address when the head changes.
Insert/delete O(1) when the position is known; access and search O(n).
Reversal, concatenation, middle node, Floyd: one pass, O(1) extra space.
Circular (last pointer), doubly linked (two directions), header node (no special cases).
The avail list reuses nodes; a circular list is returned in O(1).
Wrap-Up
References and next steps
- E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Chapter 4 (lists, avail, circular and doubly linked lists).
- T. H. Cormen et al., Introduction to Algorithms, Section 10.2 (lists with sentinels).
- D. E. Knuth, The Art of Computer Programming Vol. 2, Exercise 3.1-6 (Floyd’s cycle detection).