Kodewick
Start learning →
Patterns: arrays or linked lists10 / 50

Patterns: array lists and linked lists

Lesson 10 of 50 · Part 2 · Arrays and linked lists · about 18 minutes

This array list and linked list review covers choosing between the two, building a list by head or tail insertion, reversing it in place with three pointers, fast and slow pointers for the middle and for cycles, and merging two sorted lists.

With array lists and linked lists done, these are the kinds of problems that come up most in exams and interviews. Learn one pattern for each and you can apply it to the variations too.

Choosing: array list or linked list

First ask: what is the operation done most often on this data?

Done most oftenChooseWhy
Getting by position (element i)array listO(1); a linked list walks i steps
Inserting or deleting next to a known nodelinked listO(1); an array list moves elements
Not knowing how many in advancelinked list (or a dynamic array)no big block needed up front
Memory matters, cache-friendlyarray listno pointers stored; contiguous memory reads fast

Common trap: "linked list insert is O(1)" assumes you already have the node before it; "insert at position i" is O(n) for both: the array list is slow at moving, the linked list at finding.

Choose one

You store a whole class’s scores. The most common job is "look up student i’s score", and you almost never insert or delete. Which do you pick?

Head and tail insertion: building a list

Reading 1 2 3 4 5 in order into a list with a header node, there are two ways to insert:

  • Head insertion: each new node goes right after the header node. The list comes out reversed: 5 4 3 2 1.
  • Tail insertion: a tail pointer remembers the last node, and each new one goes after it. The order stays the same.
L↓
Hh
3c
2b
1a
NULL

Head insertion: each new node goes right after the header node H, pushing the earlier ones back; reading 1 2 3 builds 3 2 1
L↓tail↓
Hh
1a
2b
3c
NULL

Tail insertion: tail always points at the last node, and each new one goes after it, so the order stays
main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *L) {17    for (Node *p = L->next; p != NULL; p = p->next)18        printf("%d ", p->data);19    printf("\n");20}21 22int main(void) {23    // head insertion: right after the header node24    Node *A = new_node(0, NULL);25    for (int x = 1; x <= 5; x++)26        A->next = new_node(x, A->next);27    show(A);28 29    // tail insertion: after tail30    Node *B = new_node(0, NULL);31    Node *tail = B;32    for (int x = 1; x <= 5; x++) {33        tail->next = new_node(x, NULL);34        tail = tail->next;35    }36    show(B);37    return 0;38}
Output
5 4 3 2 1 
1 2 3 4 5 

So one way to reverse a linked list is to take the nodes off one by one and put them back with head insertion.

Guess the outputA wrong guess is fine

Tail insertion, but tail never moves. What does this print?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int main(void) {17    Node *L = new_node(0, NULL);18    Node *tail = L;19    for (int x = 1; x <= 3; x++)20        tail->next = new_node(x, NULL);21    for (Node *p = L->next; p != NULL; p = p->next)22        printf("%d ", p->data);23    printf("\n");24    return 0;25}

Reversing in place

With no extra memory, turn 1 → 2 → 3 into 3 → 2 → 1. The pattern is three pointers: prev (the head of the part already reversed), cur (the one being handled), and next (remembered first, so the rest isn't lost).

cur↓
1a
2b
3c
NULL

Reversing in place: each step turns cur's arrow around to point at prev
1Node *prev = NULL, *cur = head;2while (cur != NULL) {3    // 1. remember the next one4    Node *next = cur->next;5    // 2. turn around6    cur->next = prev;7    // 3. move both pointers on8    prev = cur;9    cur = next;10}11// the new head12head = prev;

Each node is touched once: O(n) time, O(1) space.

Put in orderDrag, or use the arrows

Put the 4 lines inside the loop in order so the program reverses 1 2 3 4 into 4 3 2 1.

  1. prev = cur;
  2. cur = next;
  3. cur->next = prev;
  4. Node *next = cur->next;
Should print
4 3 2 1
Exercise 1

Reverse in place

Finish reverse: reverse the list in place with three pointers and return the new head.

It should print
4 3 2 1
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *head) {17    for (Node *p = head; p != NULL; p = p->next)18        printf("%d ", p->data);19    printf("\n");20}21 22Node *reverse(Node *head) {23    Node *prev = NULL, *cur = head;24    // remember the next one, turn around, move both on25    return prev;26}27 28int main(void) {29    Node *head = new_node(1, new_node(2, new_node(3, new_node(4, NULL))));30    head = reverse(head);31    show(head);32    return 0;33}
Output
Press Run or Ctrl+Enter

Fast and slow pointers: the middle, and cycles

Two pointers start at the head together; slow takes 1 step at a time and fast takes 2. When fast reaches the end, slow is right in the middle.

slow↓fast↓
1a
2b
3c
4d
5e
NULL

Fast and slow pointers: fast takes two steps, slow one; when fast reaches the end, slow is in the middle
main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int main(void) {17    Node *head = new_node(1, new_node(2, new_node(3, new_node(4, new_node(5, NULL)))));18    Node *slow = head, *fast = head;19    while (fast != NULL && fast->next != NULL) {20        slow = slow->next;21        fast = fast->next->next;22    }23    printf("the middle is %d\n", slow->data);24    return 0;25}
Output
the middle is 3

The same pattern can also tell whether there's a cycle: if the list points back somewhere earlier, fast never reaches NULL, and it always catches up with slow from behind (the two pointers become equal).

slow↓fast↓
1a
2b
3c
4d
5e
NULL

Finding a cycle: 5 points back to 3, making a loop; slow takes 1 step, fast 2, and once both are in the loop fast gains 1 step a round, so it must catch up
Choose one

Checking for a cycle with fast and slow pointers: what are the time and the extra space?

Exercise 2

Is there a cycle

Finish has_cycle: use fast and slow pointers to tell whether the list has a cycle; return 1 if it does, 0 if not.

It should print
1 0
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int has_cycle(Node *head) {17    Node *slow = head, *fast = head;18    // while fast can, it takes two steps and slow one; equal means a cycle19    return 0;20}21 22int main(void) {23    Node *c = new_node(3, NULL);24    Node *a = new_node(1, new_node(2, c));25    Node *x = new_node(7, new_node(8, new_node(9, NULL)));26    c->next = a->next;            // 3 points back to 2: a cycle27    printf("%d %d\n", has_cycle(a), has_cycle(x));28    return 0;29}
Output
Press Run or Ctrl+Enter

Merging two sorted lists

Two lists sorted smallest first, merged into one that is still sorted. The pattern is a dummy head node plus a tail: compare the first of each side, and the smaller goes after tail.

Merging a (1 4 6, green) and b (2 3 8, blue): each node drops to its place in the merged list below, its colour saying which list it came from; the dummy in front is the fake head, and what is returned is dummy.next
1Node dummy = {0, NULL};2Node *tail = &dummy;3while (a != NULL && b != NULL) {4    if (a->data <= b->data) { tail->next = a; a = a->next; }5    else                    { tail->next = b; b = b->next; }6    tail = tail->next;7}8// attach whatever is left9tail->next = (a != NULL) ? a : b;10return dummy.next;

With a dummy head, the first node needs no special case (the same idea as the dummy head node in the lesson on inserting and deleting).

Fill inTap one to fill a blank; tap a blank to take it back

When the loop stops, one side has run out. The last line hooks up whatever is left of the other side in one go: what goes in the blank? The program should print 1 2 3 4 6 8 9.

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16Node *merge(Node *a, Node *b) {17    Node dummy = {0, NULL};18    Node *tail = &dummy;19    while (a != NULL && b != NULL) {20        if (a->data <= b->data) {21            tail->next = a;22            a = a->next;23        } else {24            tail->next = b;25            b = b->next;26        }27        tail = tail->next;28    }29    tail->next = ;30    return dummy.next;31}32 33int main(void) {34    Node *a = new_node(1, new_node(4, new_node(8, new_node(9, NULL))));35    Node *b = new_node(2, new_node(3, new_node(6, NULL)));36    for (Node *p = merge(a, b); p != NULL; p = p->next)37        printf("%d ", p->data);38    printf("\n");39    return 0;40}
Exercise 3

Merge two sorted lists

Finish merge: with a dummy head and tail, merge two lists sorted smallest first into one.

It should print
1 2 3 4 6 8 9
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *head) {17    for (Node *p = head; p != NULL; p = p->next)18        printf("%d ", p->data);19    printf("\n");20}21 22Node *merge(Node *a, Node *b) {23    Node dummy = {0, NULL};24    Node *tail = &dummy;25    // while both have nodes, the smaller goes after tail; then attach the rest26    return dummy.next;27}28 29int main(void) {30    Node *a = new_node(1, new_node(4, new_node(6, NULL)));31    Node *b = new_node(2, new_node(3, new_node(8, new_node(9, NULL))));32    show(merge(a, b));33    return 0;34}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Five linked list patterns

  • Choosing: array list for getting by position, linked list for frequent inserts and deletes
  • Head insertion builds it reversed; tail insertion needs a tail
  • Reversing: three pointers, prev, cur and next
  • Fast and slow pointers: the middle, and cycles
  • Merging sorted lists: a dummy head + tail
1next = cur->next; cur->next = prev; prev = cur; cur = next;2slow = slow->next; fast = fast->next->next;

Chapter 1 quick check

6 questions on this chapter: array lists, linked lists, dynamic arrays and the step most often written wrong. Work out what each prints before you pick.

Guess the outputA wrong guess is fine

Inserting at index 2 of an array list of length 6: how many move?

1#include <stdio.h>2 3int main(void) {4    int a[8] = {1, 2, 3, 4, 5, 6};5    int len = 6, pos = 2, moves = 0;6    for (int i = len; i > pos; i--) {7        a[i] = a[i - 1];8        moves++;9    }10    a[pos] = 9;11    printf("%d\n", moves);12    return 0;13}
Guess the outputA wrong guess is fine

p is the second node. After p->next = p->next->next, what does it print?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int main(void) {17    Node *head = new_node(1, new_node(2, new_node(3, new_node(4, NULL))));18    Node *p = head->next;19    p->next = p->next->next;20    for (Node *q = head; q != NULL; q = q->next)21        printf("%d ", q->data);22    printf("\n");23    return 0;24}
Guess the outputA wrong guess is fine

Each time head = new_node(x, head). What does it print?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int main(void) {17    Node *head = NULL;18    for (int x = 1; x <= 4; x++)19        head = new_node(x, head);20    for (Node *q = head; q != NULL; q = q->next)21        printf("%d ", q->data);22    printf("\n");23    return 0;24}
Guess the outputA wrong guess is fine

6 nodes, 1 to 6. Where is slow when the loop stops?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int main(void) {17    Node *head = NULL;18    for (int x = 6; x >= 1; x--)19        head = new_node(x, head);20    Node *slow = head, *fast = head;21    while (fast != NULL && fast->next != NULL) {22        slow = slow->next;23        fast = fast->next->next;24    }25    printf("%d\n", slow->data);26    return 0;27}
Guess the outputA wrong guess is fine

Starting at 1 slot and doubling when full, what are len and cap after 9 pushes?

1#include <stdio.h>2 3int main(void) {4    int cap = 1, len = 0;5    for (int x = 0; x < 9; x++) {6        if (len == cap)7            cap *= 2;8        len++;9    }10    printf("%d %d\n", len, cap);11    return 0;12}
Guess the outputA wrong guess is fine

The two insert steps the wrong way round: p->next first, then s->next. What are the first 4 printed?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16int main(void) {17    Node *p = new_node(1, new_node(2, NULL));18    Node *s = new_node(5, NULL);19    p->next = s;20    s->next = p->next;21    Node *q = p;22    for (int k = 0; k < 4; k++, q = q->next)23        printf("%d ", q->data);24    printf("\n");25    return 0;26}