Chapter 4: Linked Lists

Data Structures and Algorithms with C
Nodes, malloc, freeInsert at front · back · middleDeletion and searchReversing · mergingFloyd’s cycle detectionCircular and doubly linkedHeader nodesThe available space list
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Building nodes

Define a self-referential struct, check the result of malloc, release with free.

Link discipline

Insert at the front, back, middle and in order, in the right sequence, without losing a link.

Safe deletion

Delete nodes without memory leaks or dangling pointers.

Classic routines

Write reversal, merging, finding the middle and Floyd’s cycle detection with O(1) extra space.

Kinds of lists

Choose circular, doubly linked and header-node lists to fit the task.

Memory management

Reuse nodes with an available space list.

Why Lists?

When arrays fall short: links instead of shifting

Array:03182123204shifts/writes: 0List:381220link updates: 0

We insert 10 after 8. The array must shift later elements to make room; the list only changes links.

Array:0318212320420shifts/writes: 1List:381220link updates: 0

Array: 20 moved one place right (move 1).

Array:0318212312420shifts/writes: 2List:381220link updates: 0

Array: 12 moved one place right (move 2). An n-element array needs n moves in the worst case: O(n).

Array:0318210312420shifts/writes: 3List:381220link updates: 0

Array: 10 written into the freed cell.

Array:0318210312420shifts/writes: 3List:38122010link updates: 1

List: a new node is allocated and temp->link points to 12. No element moved.

Array:0318210312420shifts/writes: 3List:38122010link updates: 2

List: 8->link = temp. If the position is known, just two links: O(1).

From the instructor “If you don’t learn pointers now, you still won’t know them in your senior year.”

Why Lists?

Nodes need not sit next to each other in memory

Memory (physical)0x0F8825NULL0x1A40120x2C100x2330other data0x2C1070x0F88head = 0x1A40Logical view12725headThe order comes from the links, not the addresses.
Node = data + link

The link field holds the address of the next node; NULL in the last node.

No random access

The address of node i cannot be computed; follow the links from the head: O(i).

What is an address?

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.

NULL

A pointer that points nowhere; it represents the empty list.

From the instructor “We set the topic aside for two lectures to cover C and pointers. You may think you know pointers very well and still not follow; that is perfectly normal.”

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 NULL

Right size without repeating the type. Out of memory, malloc returns NULL; sample message: No memory, no memoryyy...

The free rule

One free per malloc; double free or use after free is undefined behavior.

From the instructor “Not every pointer needs a malloc. No such rule!”

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
Why the typedef first?

The structure contains a pointer to its own type; declaring a pointer to an incomplete type is allowed.

Naming

The pointer type can be called list_pointer, node_ptr or similar; here node_ptr.

datanextstruct node: data field + link field
Common mistake: writing 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

729listp

print_list(list): the pointer is passed by value; advancing p does not change list in main.

729listp

p is at the first node: print 7.

729listp

p = p->link: the second node.

729listp

Print 2.

729listp

The third node.

729listp

Print 9.

729listp = NULL

p == NULL: the loop ends.

729listp = NULL

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
Why node_ptr *head?

The head will change. Passed by value, only a local copy would change and list in main would stay stale.

Order matters

Writing *head = temp first would link the node to itself and lose the rest of the list. Cost O(1).

From the instructor “Normally, a variable that appears as ‘*param’ in a function’s formal parameter list should be used as ‘*param’ inside the function too.”

Singly Linked Lists · Run the code step by step

Code Trace: insert_front(&list, 5)

72list*headtemp = ?

The call: insert_front(&list, 5). head is the address of the variable list in main; the list is 7 → 2.

72??listtemp*head

malloc allocated a node on the heap. Its fields still hold garbage.

72??listtemp*head

temp != NULL: allocation succeeded, go on. (Otherwise it would return false with the list intact.)

725?listtemp*head

Fill the data field: temp->data = 5.

725listtemp*head

First keep the old head: temp->link = *head → the new node points to 7. list still points to 7.

725listtemp*head

Then change the head: *head = temp. Thanks to passing by address, list in main is updated.

725listtemp*head

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)

4165list

The new node (5) is ready; link = NULL since it will be last.

4165listp

The list is not empty: p starts at the head.

4165listp

It advances until p->link == NULL: the last node is 6. This walk is O(n).

4165listp

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

12725listprev

12 → 7 → 25; prev = node(7). Insert 9 after 7.

127259listprevp

new_node(9): node allocated, link = NULL.

127259listprevp

p->link = prev->link: 25’s address is copied into the new node; nothing lost.

127259listprevp

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

2597listtemp

We insert 7 into the sorted list 2 → 5 → 9. The new node (from malloc) is ready; temp->link is not linked yet.

2597listpprev = NULLtemp

p starts at the head; prev will trail one step behind p (NULL for now).

2597listpprev = NULL2 < 7 → truetemp

Condition: 2 < 7 → true. We must go further.

2597listprev, ptemp

prev = p → node(2).

2597listprevptemp

p = p->link → &node(5).

2597listprevp5 < 7 → truetemp

Condition: 5 < 7 → true. We must go further.

2597listprev, ptemp

prev = p → node(5).

2597listprevptemp

p = p->link → &node(9).

2597listprevp9 < 7 → falsetemp

Condition: 9 < 7 → false. The insertion point is found: between prev and p.

2597listprevptemp

First link the new node to p: temp->link = p (so the address of 9 is not lost).

2597listprevptemp

prev != NULL: we insert in the middle, not at the front; the head stays.

2597listprevptemp

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

5382listprev

To delete a node from a singly linked list we need the node before it: here 3.

5382listprevvictim

victim = prev->link: keep the address, or we could not free it.

5382listprevvictim

prev->link = victim->link: 3 now points to 2, and 8 is out of the chain.

5382listprevvictimfree

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)

3816listpprev = NULL

The list is 3 → 8 → 1 → 6; we delete x = 1. p starts at the head, prev = NULL.

3816listpprev = NULL3 != 1 → true

Condition 3 != 1 → true. Keep searching.

3816listprev, p

prev = p → node(3).

3816listprevp

p = p->link → &node(8).

3816listprevp8 != 1 → true

Condition 8 != 1 → true. Keep searching.

3816listprev, p

prev = p → node(8).

3816listprevp

p = p->link → &node(1).

3816listprevp1 != 1 → false

Condition 1 != 1 → false. The node to delete is found; prev is one step behind.

3816listprevp

p != NULL: x is in the list, go on to delete it.

3816listprevp

prev != NULL: it is not the head; *head will not change.

3816listprevp

prev->link = p->link: 8 now points to 6; 1 is bypassed.

3816listprevpfree

free(p): the node goes back to memory. Forgetting this causes a memory leak.

3816listprevpfree

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
}
Short-circuit

p != NULL && p->data != x: in the reverse order we would look inside NULL at the end of the list.

Cost

Search is O(n) in the worst case, nth(p, i) is O(i). Not O(1) like a[i] in an array.

In a sorted list

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?

Exam question. Two routines that free a list node by node (left: a common faulty version, right: the correct one). In the left one, what happens to 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.

From the instructor “What is this code? Forgotten so soon! … Once you write code you feel very sure of it. Don’t be that sure!”

Singly Linked Lists · Run the code step by step

Code Trace: free_list(&lst)

49listp*list

Call 1: p = *list → &node(4).

49listp*list

p != NULL: there is a node to free.

49listp*list

*list = p->link: lst in main is now &node(9).

49listp*listfree

free(p): node(4) is released; p is now a dangling pointer and must not be used.

49listp*listfree

Recursive call with the same list address: free the rest of the list.

49listp*listfree

Call 2: p = *list → &node(9).

49listp*listfree

p != NULL: there is a node to free.

49listp*listfree

*list = p->link: lst in main is now NULL.

49listp*listfreefree

free(p): node(9) is released; p is now a dangling pointer and must not be used.

49listp*listfreefree

Recursive call with the same list address: free the rest of the list.

49list*listfreefreep = NULL

Call 3: p = *list → NULL.

49list*listfreefreep = NULL

p == NULL: the list is done; the call returns without doing anything. Base case.

49listp*listfreefree

Back in call 2; nothing left to do.

49listp*listfreefree

Back in call 1; nothing left to do.

49list*list

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
    }
}
Recursive version

One call frame per node: with n = 10⁶ nodes the stack may overflow.

Iterative version

O(n) time, O(1) extra space; *list ends up NULL.

The common rule

Take the next address before free; never read the link of a freed node.

Classic Routines

Question: reverse the links (invert)

QUESTION. Write a routine invert that reverses the link fields of the list pointed to by list.
102030listrqpdone | to do

Midway: the part up to r and q is reversed, the part from p on still points the old way.

Three pointers

r trails, q is in the middle, p leads; each round reverses one link.

In place

No new nodes, no copies: O(n) time, O(1) extra space.

The head changes

That is why the list is passed by address as node_ptr *list.

From the instructor “No add_node, no remove_node, no malloc, no extra memory, no extra work; nothing at all!”

Classic Routines · Run the code step by step

Code Trace: invert(&list)

102030listpq = NULLr = ?

Three pointers: p leads (the head), q is in the middle (NULL), r trails (no value yet).

102030listpq = NULLr = ?

p != NULL: a round begins.

102030listpr, q = NULL

Round 1: r = q → NULL.

102030listq, pr = NULL

q = p → &node(10): the node whose link is reversed this round.

102030listqpr = NULL

p = p->link → &node(20). We advance first so the rest of the list is not lost.

102030listqpr = NULL

q->link = r: node(10) now points to NULL.

102030listqpr = NULL

p != NULL: a round begins.

102030listr, qp

Round 2: r = q → &node(10).

102030listrq, p

q = p → &node(20): the node whose link is reversed this round.

102030listrqp

p = p->link → &node(30). We advance first so the rest of the list is not lost.

102030listrqp

q->link = r: node(20) now points to node(10).

102030listrqp

p != NULL: a round begins.

102030listr, qp

Round 3: r = q → &node(20).

102030listrq, p

q = p → &node(30): the node whose link is reversed this round.

102030listrqp = NULL

p = p->link → NULL. We advance first so the rest of the list is not lost.

102030listrqp = NULL

q->link = r: node(30) now points to node(20).

102030listrqp = NULL

p == NULL: the loop ends; q is at the last node.

102030listrqp = NULL

*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

1469L1L2

L1 = 1 → 4, L2 = 6 → 9. Neither is empty.

1469L1L2p

p walks from the head of L1.

1469L1L2p

p->link == NULL: the last node of L1 is found. Cost O(|L1|).

1469L1L2p

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

12345headslowfast

Both start at the head.

12345headslowfast

slow takes 1 step, fast takes 2.

12345headslowfast

fast is at the last node (fast->link == NULL): the loop ends and slow = 3 is in the middle.

12345headslowfast

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)

The problem

A faulty link (last->link = some_middle_node) puts the list in a cycle; print_list never ends.

The idea

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.

Cost

O(n) time, O(1) extra space. Keeping visited nodes in a set also works but needs O(n) space.

Start of the cycle

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

12345headslowfast5 → 3: cycle

The tortoise (slow) and the hare (fast) start together at the head. The list has a cycle 5 → 3.

12345headslowfast5 → 3: cycle

fast and its successor are not NULL: keep running.

12345headslowfast5 → 3: cycle

Round 1: the tortoise takes 1 step → node(2).

12345headslowfast5 → 3: cycle

The hare takes 2 steps → node(3).

12345headslowfast5 → 3: cycle

Not on the same node; continue.

12345headslowfast5 → 3: cycle

fast and its successor are not NULL: keep running.

12345headslowfast5 → 3: cycle

Round 2: the tortoise takes 1 step → node(3).

12345headslowfast5 → 3: cycle

The hare takes 2 steps → node(5).

12345headslowfast5 → 3: cycle

Not on the same node; continue.

12345headslowfast5 → 3: cycle

fast and its successor are not NULL: keep running.

12345headslowfast5 → 3: cycle

Round 3: the tortoise takes 1 step → node(4).

12345headslowfast5 → 3: cycle

The hare takes 2 steps → node(4).

12345headslowfast5 → 3: cycle

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

358last
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;
}
Why last?

last->link is the first node: inserting at both the front and the back is O(1).

No NULL

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

3581?lasttemp

3 → 5 → 8 → (3), last = 8. We insert the new node 1.

3581lasttemp

temp->link = last->link: the new node points to the old first node (3).

3581lasttemp

last->link = temp: 8 now points to 1. Front insertion done: 1 → 3 → 5 → 8.

3581lasttemp

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

H38listHlistnonempty list: H → 3 → 8empty list: only H
// 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;
}
The idea

A node at the front that carries no data and is never deleted. Empty list = just the header.

The gain

Every real node has a predecessor: the *head and if (prev == NULL) special cases disappear.

Circular and Doubly Linked

The doubly linked list

HH48empty: H points to itselfH ⇄ 4 ⇄ 8 ⇄ H
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)

H486??pH: header nodetemp

A circular doubly linked list with a header node: H ⇄ 4 ⇄ 8 ⇄ H. We insert 6 to the right of 4.

H486?pH: header nodetemp

temp->llink = p: the new node’s left link points to 4.

H486pH: header nodetemp

temp->rlink = p->rlink: its right link points to 8. The list has not changed yet; only the new node is prepared.

H486pH: header nodetemp

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.)

H486pH: header nodetemp

p->rlink = temp: the last link. Four links updated, no special case: O(1).

H486pH: header node

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

H468pH: header node

H ⇄ 4 ⇄ 6 ⇄ 8 ⇄ H; p = node(6). Its predecessor is already at hand as p->llink.

H468pH: header node

p->llink->rlink = p->rlink: 4’s right is now 8.

H468pH: header node

p->rlink->llink = p->llink: 8’s left is now 4.

H468pH: header nodefree

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;
}
The idea (Horowitz)

Deleted nodes go onto the avail chain instead of to free; new nodes are taken from there first.

Why?

Programs that insert and delete a lot make fewer malloc/free calls; getting/returning a node is O(1).

Limitation

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

··9?availnode in use

The avail chain holds two free nodes; on the right, node(9) is in use.

··9?availpnode in use

get_node(): avail is not empty → p = avail. No malloc call.

··9??availpnode in use

avail = avail->link: the head of the chain moves on; p now belongs to the caller.

··9?availoldnode in use(in use)

ret_node(old): old->link = avail.

··9?availold(in use)

avail = old: the node is ready to be reused. Both are O(1), like push/pop on a linked stack.

In fact avail is a stack: get_node = pop, ret_node = push.

Memory Management · Step by step

Returning a circular list in one move (Horowitz: cerase)

358·lastavailfirst

3 → 5 → 8 → (3), last = 8; avail holds one node. first = last->link = 3.

358·lastavailfirst

last->link = avail: the ring is opened and its end joined to the avail chain.

358·lastavailfirst

avail = first: the whole list now sits in front of avail.

358·lastavailfirst

*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

OperationArraySingly linked (head)Circular (last)Doubly linked (header)
Access the i-th elementO(1)O(i)O(i)O(i)
Insert at frontO(n)O(1)O(1)O(1)
Insert at backO(1)*O(n)O(1)O(1)
Insert after a known nodeO(n)O(1)O(1)O(1)
Delete a known nodeO(n)O(n)†O(n)†O(1)
Search by valueO(n)O(n)O(n)O(n)
ConcatenateO(n+m)O(n)O(1)O(1)
Extra space per node—1 pointer1 pointer2 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

1Overwriting a link before saving it: write p->link = temp first and the rest of the list is lost.
2Passing the pointer by value to a routine that changes the head (node_ptr head); the list in main is not updated.
3Not checking the result of malloc; forgetting free (a leak) or calling it twice.
4Reading the link of a freed node; save the successor first, then free.
5Not testing the empty list, a single node, and the head/tail cases.
6Traversing a circular list with p != NULL: the loop never ends.

Wrap-Up

Exercises

  1. Merge two sorted lists into one sorted list without allocating nodes.
  2. Find the k-th node from the end of a list in a single pass.
  3. Delete the duplicates from a sorted list; return the deleted nodes with ret_node.
  4. Write invert recursively. What is the extra space?
  5. After Floyd finds a cycle, compute the length of the cycle.
Answers / hints
  1. 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).
  2. Move the fast pointer k steps ahead, then walk both together.
  3. While a neighbor is equal, delete_next(p); O(n).
  4. Reverse the rest, then p->link->link = p; p->link = NULL; O(n) because of the stack.
  5. Count from the meeting node until you return to it.
From the instructor “If I hold your homework over mine against the light… (there should be no difference)”

Wrap-Up

Chapter summary

Node + link

List elements are scattered; the order is built with link fields. Empty list = NULL.

Link discipline

Save first, link next, release (free) last. Pass by address when the head changes.

Costs

Insert/delete O(1) when the position is known; access and search O(n).

Classics

Reversal, concatenation, middle node, Floyd: one pass, O(1) extra space.

Kinds

Circular (last pointer), doubly linked (two directions), header node (no special cases).

Memory

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).

The End

Chapter 4: Linked Lists
Next chapter: Chapter 5: Polynomials and Sparse Matrices · Course page
1 / 1 Data Structures in C