← The C Language Lesson 74 of 77 · 10 XP

Linked lists

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A linked list is a chain of nodes on the heap, where each node holds a value and a pointer to the next one:

struct node {
    int value;
    struct node *next;
};
head → [1|•] → [2|•] → [3|NULL]

Unlike in an array, the items don't lie next to each other. Inserting and removing at the start costs O(1) and doesn't require moving the other items. But getting to the i-th item takes i steps.

Adding to the start:

struct node *push_front(struct node *head, int value)
{
    struct node *n = malloc(sizeof *n);
    n->value = value;
    n->next = head;
    return n;            // the new head
}

Walking through and freeing:

for (struct node *p = head; p != NULL; p = p->next)
    printf("%d ", p->value);

while (head) {
    struct node *next = head->next;   // remember it BEFORE free
    free(head);
    head = next;
}

Linked lists are an interview classic and the basis of many structures in the Linux kernel.

Task. Read numbers until the end of the input and store them in a linked list in the original order (add to the end, keeping a pointer to the tail). Then reverse the list by re-pointing the pointers (without allocating new memory), and print the items separated by spaces. Free all the memory.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.