Chapter 9: The List ADT and Generalized Lists
Introduction
Learning Outcomes
Define the list ADT by its operations, preconditions, and postconditions; separate the implementation from the interface.
Compare array and linked implementations on access, insertion, and memory.
Define lists that contain atoms and sublists, and draw their memory layout.
Write and trace recursive copy, equality, traversal, depth, and inversion.
Turn a tree into a one-line linear form and explain the method's limits.
Explain the pitfalls of shared and recursive lists, and the ideas behind reference counting and garbage collection.
The List ADT
The list ADT: what it does, with the how hidden
typedef struct list List; // opaque type List *list_create(void); void list_destroy(List *L); int list_length(const List *L); bool list_get(const List *L, int i, int *x); bool list_insert(List *L, int i, int x); // 0<=i<=n bool list_delete(List *L, int i, int *x); // 0<=i<n int list_find(const List *L, int x); // -1 if absent
L = (a0, a1, …, an−1), n ≥ 0; ai comes before ai+1.
list_insert(L, i, x): before, 0 ≤ i ≤ n; after, x is at position i, the length is n+1, and the old ai, …, an−1 have each moved one place right.
struct list is defined only in the .c file; client code can't tell whether it is an array or links, so swapping implementations is easy.
The List ADT
Array implementation (sequential mapping)
#define CAPACITY 100 typedef struct { int a[CAPACITY]; int n; // item count } ArrayList; bool array_delete(ArrayList *L, int i, int *x) { int k; if (i < 0 || i >= L->n) return false; *x = L->a[i]; for (k = i; k < L->n - 1; k++) L->a[k] = L->a[k + 1]; // shift left L->n--; return true; }
The address of a[i] is computed: O(1).
The items after i must shift: O(n) in the worst case (insert or delete at the front).
A fixed array fills up; doubling a dynamic array with realloc gives O(1) insertion on average.
The List ADT · Run the code step by step
Code Trace: array_insert(&L, 1, 9)
List [4, 7, 2], n = 3; 9 is to be inserted at position 1 (0-based).
Check: not full, and 0 ≤ i ≤ n; we can insert.
k = 3: k > i → true, shift.
a[3] = a[2]: 2 moved one place right.
k = 2: k > i → true, shift.
a[2] = a[1]: 7 moved one place right.
k = 1: k > i → false, the loop ends.
a[i] = x: 9 is written into the freed slot.
n++: the list is [4, 9, 7, 2]. The number of shifts is n − i: O(n) in the worst case (i = 0).
bool array_insert(ArrayList *L, int i, int x) { int k; if (L->n == CAPACITY || i < 0 || i > L->n) return false; // full/invalid for (k = L->n; k > i; k--) L->a[k] = L->a[k - 1]; // shift right L->a[i] = x; L->n++; return true; }
The List ADT
Linked implementation: a pointer to a pointer
typedef struct node *node_pointer; struct node { int data; node_pointer link; }; typedef struct { node_pointer head; int n; } LinkedList; bool ll_insert(LinkedList *L, int i, int x) { node_pointer *pp = &L->head, new_node; if (i < 0 || i > L->n) return false; while (i-- > 0) pp = &(*pp)->link; // walk to link i new_node = malloc(sizeof *new_node); if (new_node == NULL) return false; new_node->data = x; new_node->link = *pp; *pp = new_node; // head or middle: same L->n++; return true; }
node_pointer *ppThe address of the link to change: first &L->head, then &prev->link. Inserting at the head stops being a special case.
Walking to the position is O(i); linking is O(1). No shifting, no capacity limit.
If an n field is kept, list_length is O(1).
The List ADT
Array or linked list?
| Criterion | Array (sequential) | Singly linked list |
|---|---|---|
| Access the i-th item | O(1) | O(i) |
| Insert / delete at the front | O(n) shifting | O(1) |
| Append at the end | O(1)* (if room) | O(n), O(1) with a tail pointer |
| Insert at a known position | O(n) | O(1) (if the predecessor is known) |
| Search (unsorted) | O(n) | O(n) |
| Search (sorted) | O(log n) binary search | O(n) |
| Memory | Data only; unused capacity | A pointer per node |
| Cache behavior | Contiguous: very good | Scattered: poor |
Generalized Lists
From linear lists to generalized lists
A = (α0, …, αn−1): every element is an atom (arrays, singly linked lists).
If each αi may be an atom or a sublist, A is a generalized list. A is the list's name and n its length.
α0 is the head of the list and (α1, …, αn−1) its tail. The tail is always a list.
Head/tail are LISP's car/cdr; LISP programs are themselves generalized lists.
| List | Length | Description |
|---|---|---|
| D = () | 0 | empty list |
| A = (a, (b, c)) | 2 | first element an atom, second the sublist (b, c); head(A) = a, tail(A) = ((b, c)) |
| B = (A, A, ()) | 3 | a shared sublist: the first two elements are the same A; the third is the empty list |
| C = (a, C) | 2 | a recursive list: it contains itself, C = (a, (a, (a, …))) |
Generalized Lists
Example: a multivariate polynomial
typedef enum { VAR, PTR, NO } tag_t; typedef struct pnode *poly_pointer; struct pnode { tag_t tag; // three kinds union { char var; // VAR: variable name poly_pointer dlink; // PTR: coef is a list int coef; // NO : integer coef }; int exp; // exponent poly_pointer link; };
VAR: list header, the variable's name (exp = 0). PTR: the coefficient is a sublist. NO: the coefficient is an integer.
P(x,y,z) is first grouped by z; each z-term's coefficient is a polynomial in y, and theirs are polynomials in x.
Generalized Lists
The polynomial's memory layout
VAR: list header, the variable's name in var. PTR: the coefficient is the list in dlink. NO: the coefficient is an integer.
P(x,y,z) = x¹⁰y³z² + 2x⁸y³z² + 3x⁸y²z² + x⁴y⁴z + 6x³y⁴z + 2yz, grouped by z and laid out as nested lists.
Lower levels are abbreviated to keep the drawing simple.
Generalized Lists
Node structure and memory layout
typedef enum { FALSE, TRUE } boolean; typedef struct list_node *list_pointer; struct list_node { boolean tag; // FALSE: atom union { char data; // atom value list_pointer dlink; // sublist head }; list_pointer link; // next on this level };
[tag | data/dlink | link]: F = atom, T = sublist.
Every routine uses this structure (nodes with a tag field).
The anonymous union is a C11 feature; for C99, name the union and write L->u.data.
Generalized Lists
Why generalized lists?
Hierarchical data such as a tree fits in the space of a one-line string: a kind of compression.
File-system directories, popup menus, nested XML/JSON, LISP expressions.
We move the data into a structure we know well; now every list routine is available.
Basic Routines
QUESTION: copy a list with no sharing and no recursion
list_pointer copy(list_pointer L) {
list_pointer q = NULL;
if (L) { // L not NULL?
q = get_node(); // get a node
q->tag = L->tag;
if (!L->tag) q->data = L->data; // atom
else q->dlink = copy(L->dlink);
q->link = copy(L->link);
}
return q;
}For each node, get a new node and copy the tag; for an atom copy the value, otherwise link in a copy of the sublist; then copy the rest.
The routine is correct only for unshared lists; a shared sublist is copied separately everywhere it is referenced.
get_node(): a helper doing malloc(sizeof *p) plus a NULL check (it stops the program when memory runs out).
Basic Routines · Run the code step by step
Code Trace: copy(L), L = (a,(b,c))
get_node(): a new node is allocated for a (its fields are still garbage).
Atom: q->tag = FALSE, q->data = 'a'.
Call for the next node: copy(L->link).
get_node(): a new node is allocated for (b,c) (its fields are still garbage).
Sublist: first ask for a copy of the sublist (a recursive call).
get_node(): a new node is allocated for b (its fields are still garbage).
Atom: q->tag = FALSE, q->data = 'b'.
Call for the next node: copy(L->link).
get_node(): a new node is allocated for c (its fields are still garbage).
Atom: q->tag = FALSE, q->data = 'c'.
Call for the next node: copy(L->link).
copy(NULL) (link): L is NULL → returns q = NULL without allocating anything.
Return: q->link = NULL (the last node).
Return: q->link ← &clone(c).
Return: q->dlink ← the sublist's copy &clone(b).
Call for the next node: copy(L->link).
copy(NULL) (link): L is NULL → returns q = NULL without allocating anything.
Return: q->link = NULL (the last node).
Return: q->link ← &clone((b,c)).
The copy is done: the same structure, built from new nodes. Nodes are taken front to back and filled in back to front.
list_pointer copy(list_pointer L) {
list_pointer q = NULL;
if (L) { // L not NULL?
q = get_node(); // get a node
q->tag = L->tag;
if (!L->tag) q->data = L->data; // atom
else q->dlink = copy(L->dlink);
q->link = copy(L->link);
}
return q;
}Basic Routines
Copying: a test list and the limits
For testing: L = ((a,b),((c,d),e))
Copying B = (A,A,()) copies A twice; the sharing is lost in the copy.
For C = (a,C) the calls never end; the stack overflows and the program crashes.
Basic Routines
QUESTION: are two lists (no sharing, no recursion) equal?
boolean equal(list_pointer T, list_pointer L) {
boolean x = TRUE;
if (!T && !L) return TRUE;
if (T && L && T->tag == L->tag) {
if (!T->tag) // atoms?
x = (T->data == L->data) ? TRUE : FALSE;
else // sublists
x = equal(T->dlink, L->dlink);
if (x == TRUE) return equal(T->link, L->link);
}
return FALSE;
}Equal if both end together. If the tags match: compare values for atoms and recurse for sublists; then compare the rest.
On recursive lists (C = (a,C)) the calls go on forever.
Basic Routines · Run the code step by step
Code Trace: equal(T, L)
Both exist and their tag fields match: compare the contents.
Atom: 'a' == 'a' → x = TRUE.
x is true: compare the rest of the nodes (the link fields).
Both exist and their tag fields match: compare the contents.
Sublist: compare the sublists first.
Both exist and their tag fields match: compare the contents.
Atom: 'b' == 'b' → x = TRUE.
x is true: compare the rest of the nodes (the link fields).
Both exist and their tag fields match: compare the contents.
Atom: 'c' == 'd' → x = FALSE.
x is false: return FALSE; the rest of the nodes is never examined.
The return value is passed straight up: FALSE.
From the sublists: x = FALSE.
x is false: return FALSE; the rest of the nodes is never examined.
The return value is passed straight up: FALSE.
boolean equal(list_pointer T, list_pointer L) {
boolean x = TRUE;
if (!T && !L) return TRUE;
if (T && L && T->tag == L->tag) {
if (!T->tag) // atoms?
x = (T->data == L->data) ? TRUE : FALSE;
else // sublists
x = equal(T->dlink, L->dlink);
if (x == TRUE) return equal(T->link, L->link);
}
return FALSE;
}Basic Routines
A better version, and shared lists
bool same(list_pointer T, list_pointer L) { if (T == L) return true; // same node/both NULL if (!T || !L || T->tag != L->tag) return false; if (T->tag ? !same(T->dlink, L->dlink) : T->data != L->data) return false; return same(T->link, L->link); }
T == L shortcutIf both are NULL or point to the same (shared) sublist, return TRUE without descending into it.
The same routine also gives the right answer for non-recursive (acyclic) shared lists; the shortcut avoids walking common sublists again.
Basic Routines
QUESTION: traverse the list and print its atoms
A common buggy version
void print_atoms( list_pointer L ){ if(L) if(!L->tag) printf("%c", L->data); else print(L->dlink); print( L->link ); }
Fixed
void print_atoms(list_pointer L) { if (L) { if (!L->tag) printf("%c", L->data); // print an atom else print_atoms(L->dlink); print_atoms(L->link); } }
print, but the routine is called print_atoms (it won't compile). (2) No braces: if(L) covers only the inner if-else, so line 7 runs even when L == NULL → crash on NULL->link. The fix is to put both calls inside if (L) { … }.Basic Routines · Run the code step by step
Code Trace: print_atoms(L), L = (a,(b),c)
Atom: 'a' printed.
Move to the next node on the same level (L->link).
Sublist: descend into it first (L->dlink).
Atom: 'b' printed.
Move to the next node on the same level (L->link).
L == NULL (end of the level): return without doing anything.
Move to the next node on the same level (L->link).
Atom: 'c' printed.
Move to the next node on the same level (L->link).
L == NULL (end of the level): return without doing anything.
All atoms are printed left to right regardless of depth: abc. Each node once: O(n).
void print_atoms(list_pointer L) { if (L) { if (!L->tag) printf("%c", L->data); // print an atom else print_atoms(L->dlink); print_atoms(L->link); } }
Basic Routines
Example: A(B(E(K,L),F),C(G),D(H(M),I,J))
Each tree node is a sublist: its head is the node's label, the rest are its children. Nodes on the same level can be followed along one row.
print_atoms prints ABEKLFCGDHMIJ: the tree's preorder traversal.Depth and Inversion
QUESTION: the depth of a list, recursively
int depth(list_pointer L) { list_pointer p = L; int m = 0; // m: the max if (!L) return 0; while (p) { if (p->tag) { int n = depth(p->dlink); if (m < n) m = n; } p = p->link; } return m + 1; }
depth(()) = 0; otherwise 1 + the largest depth among the sublists. Atoms add no depth.
(a, b) → 1 · (a, (b, c)) → 2 · (a, (b, (c))) → 3 · (()) → 1.
Each node is visited once: O(n); the call stack grows at most as deep as the list.
Depth and Inversion · Run the code step by step
Code Trace: depth(L), L = (a,(b,(c)))
Level 1 call: p = L, m = 0.
'a' is an atom: no added depth.
Found a sublist: its depth is computed recursively.
Level 2 call: p = L, m = 0.
'b' is an atom: no added depth.
Found a sublist: its depth is computed recursively.
Level 3 call: p = L, m = 0.
'c' is an atom: no added depth.
p = p->link → NULL: this level is done.
return m + 1 = 1: the deepest sublist + this level.
The sublist returned n = 1 → m = 1.
p = p->link → NULL: this level is done.
return m + 1 = 2: the deepest sublist + this level.
The sublist returned n = 2 → m = 2.
p = p->link → NULL: this level is done.
return m + 1 = 3: the deepest sublist + this level.
int depth(list_pointer L) { list_pointer p = L; int m = 0; // m: the max if (!L) return 0; while (p) { if (p->tag) { int n = depth(p->dlink); if (m < n) m = n; } p = p->link; } return m + 1; }
Depth and Inversion
QUESTION: depth, iteratively (a student solution)
int depth( tree_pointer L ){ tree_pointer pop(); void push(tree_pointer); int max = 0; for( int current = 1, p = L ; p ; p->link ){ if( p->tag ){ // enter the sublist push(p); p = p -> dlink; current++; } if( !p->link ){ // end of list, go up p = pop(); if( max < current ) max = current; current--; } } return max; }
int current = 1, p = L makes p an int; the update p->link is not an assignment → an infinite loop.
It dereferences NULL on an empty sublist, pops an empty stack, and never moves on to T's sibling.
Depth and Inversion
Iterative depth with a local stack
int iter_depth(list_pointer L) { list_pointer stack[100]; // local stack (depth<100) int top = 0, d = 1, m = 0; list_pointer p = L; if (!L) return 0; for (;;) { if (p == NULL) { // level done if (top == 0) return m; p = stack[--top]->link; // the node after T d--; } else { if (d > m) m = d; if (p->tag && p->dlink) { stack[top++] = p; // descend p = p->dlink; d++; } else p = p->link; } } }
When descending into a sublist, push its T node; when the level ends, pop it and move on to its sibling.
No globals: the stack and counters are local. The empty sublist and the empty list are handled separately.
Checked by simulation to match the recursive version on six sample lists.
Depth and Inversion
On thinking recursively
Edge-case lists: (), (a), (()), ((())), a long one-level list, a deep single chain.
Depth and Inversion
QUESTION: invert an unshared list — L = (a,(b,c)) → ((c,b),a)
void invert(list_pointer *L) { list_pointer r, p = *L, q = NULL; while (p) { if (p->tag) // not an atom invert(&p->dlink); r = q; q = p; p = p->link; q->link = r; } *L = q; }
The three pointers of the singly linked list_invert routine, unchanged; the addition: if the node is a sublist, invert it first. Use: mirroring an image.
&p->dlink?The sublist's head changes; the T node's dlink field is updated by the inner call's *L = q line before the call returns.
Depth and Inversion · Run the code step by step
Code Trace: invert(&L), (a,(b,c)) → ((c,b),a)
p = *L → &node(a), q = NULL.
r = q; q = p; p = p->link; q->link = r; → a's link is reversed.
The node is a sublist: invert it first (via the address &p->dlink).
p = *L → &node(b), q = NULL.
r = q; q = p; p = p->link; q->link = r; → b's link is reversed.
r = q; q = p; p = p->link; q->link = r; → c's link is reversed.
p == NULL: this level is done.
*L = q: c is this level's new head.
Back from the sublist: the T node's dlink already points to the new head.
r = q; q = p; p = p->link; q->link = r; → (c,b)'s link is reversed.
p == NULL: this level is done.
*L = q: (c,b) is this level's new head.
void invert(list_pointer *L) { list_pointer r, p = *L, q = NULL; while (p) { if (p->tag) // not an atom invert(&p->dlink); r = q; q = p; p = p->link; q->link = r; } *L = q; }
Depth and Inversion
Data structures: the backbone
Trees and Sharing
Building a tree structure with a generalized list
A(B(E(K,L),F),C(G),D(H(M),I,J))
C(G): C is G's parent. A(B…,C…,D…): A is the parent of B, C, and D.
For this much data a one-line string is enough. Dots instead of commas, braces instead of parentheses: the notation is up to you.
Trees and Sharing
Drawback: no left/right distinction
All three trees have the same linear form, A(B(C(D(E),G(I)))): there is no way to write whether B is a left or a right child.
For a general tree the order of children is enough, but in a binary tree the distinction between left and right children is lost.
Store L/R information with each node (or write a special symbol for an empty child): A(B(,C(…))).
Trees and Sharing
Assignments
- Assignment 1: Draw the memory layout and the tree structure of the list
A(B(E(H,I(J,K)),F),C(G),D). - Assignment 2: Write a routine that, given a tree structure, outputs its list notation.
Suggested solutions
void print_tree(list_pointer L) { // L: (root, subtrees...) printf("%c", L->data); // root label if (L->link) { printf("("); for (list_pointer p = L->link; p; p = p->link) { if (p->tag) print_tree(p->dlink); else printf("%c", p->data); // leaf if (p->link) printf(","); } printf(")"); } }
Assignment 2: if the tree is stored as a list whose first element is the root label, print_tree produces the right text for both examples (checked by simulation).
Trees and Sharing
Shared lists and reference counting
// header ref: how many pointers point to this list void list_free(list_pointer *L) { list_pointer p, q; if (*L == NULL) return; if (--(*L)->ref > 0) { // still in use *L = NULL; return; } p = (*L)->link; // first real node free(*L); while (p) { if (p->tag) list_free(&p->dlink); q = p; p = p->link; free(q); } *L = NULL; }
Every list starts with a header node; ref is the number of pointers pointing to it.
A list is not freed until its count reaches 0; when it does, its nodes and sublists are released by the same rule.
Horowitz–Sahni, Section 4.9 (header nodes with reference counts).
Trees and Sharing
Reference counting step by step: B = (A, A, ())
Each list starts with a header node; ref is the number of pointers to it. A is pointed to by the name A and by two of B's elements: 3.
list_free(&B): B's count goes 1 → 0, and B's nodes are released one by one.
B's two T nodes call list_free on A: 3 → 2 → 1. A is still in use, so it is not freed.
Then list_free(&A): 1 → 0, and A is freed. Sharing handled safely.
Trees and Sharing
The limits of reference counting, and garbage collection
C = (a, C): C points to itself, so its count never reaches 0; even if the name C is deleted, the list stays in memory (a leak).
(1) Every node reachable from the root pointers (variables) is marked; (2) memory is scanned and unmarked nodes are swept (returned to avail).
The program pauses while the collector runs, and the mark bit needs space. LISP, Java, and Python use variants of this idea.
No automatic garbage collection: copying, sharing, and freeing are the programmer's responsibility.
Lab · C code step by step
Lab: List Depth
Wrap-Up
Exam question
int count has been added to each node. Write a recursive routine that stores, in the count of every node whose tag is TRUE, the number of nodes below it, and returns the total number of nodes.Sample solution
int count_nodes(list_pointer L) { int total = 0; // an empty list has 0 nodes for (; L; L = L->link) { if (L->tag) { // is there a sublist? L->count = count_nodes(L->dlink); total += L->count; // count the sublist's nodes too } total++; // the current node } return total; }
Example: (a,(b,c)) → the T node's count is 2 and the return value is 4 (the T node counts too). Checked by simulation.
Wrap-Up
Exam question
Solution
void print_linear(list_pointer L) { printf("("); for (; L; L = L->link) { if (L->tag) print_linear(L->dlink); else printf("%c", L->data); if (L->link) printf(","); } printf(")"); }
An empty sublist prints as () too: (a,(()),b) is reproduced exactly (checked by simulation).
Wrap-Up
Exam question
L=(d,(c,(e,(m,k),(()),z,y,(x,(r),b,a,())))). Consecutive elements on the same level must be traceable along one row.Solution
(()): a one-element list whose sublist is the empty list; the last element (): a T node with dlink = NULL.
Wrap-Up
Complexity summary
| Routine | Time | Extra memory | Note |
|---|---|---|---|
| copy | O(n) | O(depth + length)* | no sharing, no recursion |
| equal / same | O(n) | O(depth + length)* | stops at the first difference |
| print_atoms | O(n) | O(depth + length)* | preorder |
| depth (recursive) | O(n) | O(depth) | loop over a level, recursion into sublists |
| iter_depth (iterative) | O(n) | O(depth) | local stack |
| invert | O(n) | O(depth) | in place, no malloc |
| array_insert / array_delete | O(n) | O(1) | shifting |
| ll_insert (position i) | O(i) | O(1) | no shifting |
n: total number of nodes. * For routines that also recurse through link, the stack depth also depends on the number of nodes on a level; using a loop for link brings it down to O(depth).
Wrap-Up
Common mistakes
ifs and recursing on NULL too (print_atoms).list_pointer *L).() with the empty list NULL: the T node exists, its dlink is NULL.Wrap-Up
Exercises
- Write a routine that counts the atoms in a generalized list.
- Write a routine that reads the linear form (
"(a,(b,c))") and builds the list. - How would you change
copyso it preserves sharing? - Write
contains(L, x), which tells whether atom x occurs in the list. - Rewrite the array-based list so that it doubles when full.
Answers / hints
- 1 for an atom, the recursive result for a sublist; sum along
link. - A recursive parser: on '(' build a sublist, advance on ',', return on ')'.
- Keep a table of the sublists already copied (old address → new address).
- Compare at an atom, search recursively in a sublist; return on the first hit.
realloc(a, 2*cap*sizeof *a); O(1) insertion on average.
Wrap-Up
Chapter summary
The contract is fixed; the implementation can change: arrays give fast access, links give fast insertion and deletion.
A node is an atom or a sublist: [tag | data/dlink | link].
Process an atom, recurse into a sublist, then continue along link.
The recursive versions are short and correct; the iterative ones need a local stack.
A one-line linear form; for binary trees, left/right information must be added.
Copying and freeing have pitfalls; reference counting fails on cycles, so garbage collection is needed.
Wrap-Up
References and next steps
- E. Horowitz, S. Sahni, S. Anderson-Freed, Fundamentals of Data Structures in C, 2nd ed., Section 4.9 (generalized lists, reference counts).
- T. H. Cormen et al., Introduction to Algorithms, Chapter 10 (list implementations).
- R. Johnsonbaugh, Discrete Mathematics (recommended in the reading).
Singly linked list routines and the list-freeing exam question: Linked Lists.