Fundamental data structures in C: linked list, stack, and queue.
| Structure | Characteristic | Example use |
|---|---|---|
| Linked list | Nodes linked by pointers; fast insertion/deletion | Ordered data with frequent insert/remove |
| Stack | Last-in, first-out (LIFO) | Function calls, Undo history |
| Queue | First-in, first-out (FIFO) | Print queue, task scheduling |
typedef struct Node { int data; // the stored data struct Node *next; // pointer to the next node } Node;
// (1) Create a node Node* createNode(int val) { Node *n = malloc(sizeof(Node)); n->data = val; n->next = NULL; return n; } // (2) Insert at the front (O(1) — fast!) void pushFront(Node **head, int val) { Node *n = createNode(val); n->next = *head; // new node's next = old head *head = n; // head now points to new node } // (3) Print all elements void printList(Node *head) { for (Node *p = head; p != NULL; p = p->next) printf("%d → ", p->data); printf("NULL\n"); } // (4) Free the memory (forgetting leaks!) void freeList(Node *head) { while (head) { Node *tmp = head->next; free(head); head = tmp; } }
// push: add to the top void push(Node **top, int val) { Node *n = createNode(val); n->next = *top; *top = n; } // pop: remove from the top int pop(Node **top) { if (*top == NULL) return -1; Node *tmp = *top; int val = tmp->data; *top = tmp->next; free(tmp); return val; }
// enqueue: add to the tail void enqueue(Node **head, Node **tail, int val) { Node *n = createNode(val); if (*tail) (*tail)->next = n; else *head = n; *tail = n; } // dequeue: remove from the head int dequeue(Node **head, Node **tail) { if (!*head) return -1; Node *tmp = *head; int val = tmp->data; *head = tmp->next; if (!*head) *tail = NULL; free(tmp); return val; }
| Operation | Array | Linked list | Stack | Queue |
|---|---|---|---|---|
| Insert at front | O(n) | O(1) | — | — |
| Append at back | O(1) | O(1)* | O(1) | O(1) |
| Random access | O(1) | O(n) | — | — |
| Insert in middle | O(n) | O(1)† | — | — |
Check your understanding of this lesson.
Insertion and deletion in a linked list just rewire pointers. Arrays have to shift elements around, which is slow.
A stack is LIFO (Last In, First Out) — the most recently pushed item is the first one you pop off.
A queue is FIFO (First In, First Out) — just like a line at a checkout.