Linked List

A linked list is a chain of nodes, each holding data and a pointer to the next node. Unlike an array, its size can grow and shrink at runtime.

head102030NULLdatanext
Each node holds data and a pointer to the next node

Singly Linked List in C

C
#include <stdio.h>
#include <stdlib.h>

struct Node { int data; struct Node *next; };

struct Node* push(struct Node *head, int x) {         // insert at beginning
    struct Node *n = malloc(sizeof(struct Node));
    n->data = x; n->next = head;
    return n;
}
struct Node* append(struct Node *head, int x) {       // insert at end
    struct Node *n = malloc(sizeof(struct Node));
    n->data = x; n->next = NULL;
    if (!head) return n;
    struct Node *t = head;
    while (t->next) t = t->next;
    t->next = n;
    return head;
}
struct Node* reverse(struct Node *head) {
    struct Node *prev = NULL, *cur = head, *nxt;
    while (cur) { nxt = cur->next; cur->next = prev; prev = cur; cur = nxt; }
    return prev;
}
void print(struct Node *h) {
    for (; h; h = h->next) printf("%d -> ", h->data);
    printf("NULL\n");
}

int main() {
    struct Node *head = NULL;
    head = append(head, 20);
    head = append(head, 30);
    head = push(head, 10);
    print(head);
    head = reverse(head);
    print(head);
    return 0;
}
10 -> 20 -> 30 -> NULL 30 -> 20 -> 10 -> NULL

Types of Linked Lists

TypeFeature
SinglyOne next pointer
Doublyprev and next, so it can be traversed both ways
CircularLast node points back to the first
Circular doublyBoth of the above
Track your progress through the Data Structures course