Add P(x) = 3x⁴ + 2x² − 5 and Q(x) = 4x³ − 2x² + x + 8, both stored as linked lists of (coefficient, exponent) nodes in decreasing order of exponent.
A linked list stores elements in nodes scattered through memory, each holding data and a pointer to the next node. It grows and shrinks at run time and inserts or deletes in O(1) once the position is reached, at the price of O(n) sequential access.
struct Node *next) — a self-referential structure; head points to the first node, the last node's link is NULL.N->next = P->next; then P->next = N; — reversing the order loses the rest of the list.An array keeps its elements in one contiguous block, so the address of element i is simply base + i × (element size) and any element is reached in O(1). The price is rigidity: the size is fixed when the block is allocated, and inserting at the front of a 1,000-element array means shifting all 1,000 elements one place to the right.
A linked list is a linear collection of nodes in which the order is given by pointers instead of by physical position. Each node has an information (data) field and a link (next) field holding the address of the following node. A separate pointer, the head (also called start or first), holds the address of the first node, and the last node's link is NULL. An empty list is simply head == NULL. Because nodes are created with malloc() and released with free() while the program runs, a linked list is a dynamic data structure.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data; /* information field */
struct Node *next; /* link field: address of the next node */
};
struct Node *createNode(int value) {
struct Node *p = malloc(sizeof(struct Node));
if (p == NULL) { /* heap exhausted: overflow */
fprintf(stderr, "Out of memory\n");
exit(1);
}
p->data = value;
p->next = NULL;
return p;
}| Term | Meaning |
|---|---|
| Node | one element: data field(s) plus one or more link fields |
| Head / start pointer | external pointer holding the address of the first node |
| Tail | the last node (some implementations keep a tail pointer too) |
| NULL link | marks the end of a non-circular list |
| Self-referential structure | a struct with a member that points to the same struct type |
| Overflow / underflow | malloc returns NULL (no free memory) / deleting from an empty list |
| Homogeneous vs heterogeneous list | all nodes of the same type vs nodes of different types (e.g. via a type tag or union) |
Every operation is built on one traversal pattern: start a pointer at the head and follow links until it becomes NULL — for (p = head; p != NULL; p = p->next). Functions that may change the head (inserting or deleting at the front) receive the address of the head pointer — a pointer to a pointer, called as insertFront(&head, 10) — so that the caller's head is updated.
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
struct Node *createNode(int v) {
struct Node *p = malloc(sizeof *p);
if (!p) { perror("malloc"); exit(1); }
p->data = v; p->next = NULL;
return p;
}
void insertFront(struct Node **head, int v) { /* O(1) */
struct Node *p = createNode(v);
p->next = *head;
*head = p;
}
void insertEnd(struct Node **head, int v) { /* O(n): walk to the last node */
struct Node *p = createNode(v), *t = *head;
if (t == NULL) { *head = p; return; }
while (t->next != NULL) t = t->next;
t->next = p;
}
void insertAt(struct Node **head, int v, int pos) { /* new node becomes position pos */
if (pos <= 1 || *head == NULL) { insertFront(head, v); return; }
struct Node *t = *head;
for (int i = 1; i < pos - 1 && t->next != NULL; i++) t = t->next; /* node pos-1 */
struct Node *p = createNode(v);
p->next = t->next; /* 1: new node takes over the rest of the list */
t->next = p; /* 2: predecessor now points to the new node */
}
int deleteValue(struct Node **head, int v) { /* returns 1 if a node was deleted */
struct Node *cur = *head, *prev = NULL;
while (cur != NULL && cur->data != v) { prev = cur; cur = cur->next; }
if (cur == NULL) return 0; /* not found (or empty list) */
if (prev == NULL) *head = cur->next; /* deleting the first node */
else prev->next = cur->next; /* bypass the node */
free(cur);
return 1;
}
int search(struct Node *head, int v) { /* 1-based position, 0 if absent */
for (int pos = 1; head != NULL; head = head->next, pos++)
if (head->data == v) return pos;
return 0;
}
int length(struct Node *head) {
int n = 0;
for (; head != NULL; head = head->next) n++;
return n;
}
void display(struct Node *head) {
for (; head != NULL; head = head->next) printf("%d -> ", head->data);
printf("NULL\n");
}
int main(void) {
struct Node *head = NULL;
insertEnd(&head, 20);
insertEnd(&head, 40);
insertFront(&head, 10);
insertAt(&head, 30, 3);
display(head); /* 10 -> 20 -> 30 -> 40 -> NULL */
printf("length=%d, 30 is at position %d\n", length(head), search(head, 30));
deleteValue(&head, 10);
deleteValue(&head, 30);
display(head); /* 20 -> 40 -> NULL */
return 0;
}| Operation | Time | Note |
|---|---|---|
| Insert at front / delete first node | O(1) | only the head changes |
| Insert at end | O(n) | O(1) if a tail pointer is maintained |
| Insert after a given node | O(1) | two link assignments |
| Insert at position k / access k-th node | O(k) | walk k − 1 links |
| Delete a node holding value x | O(n) | search for it while remembering the predecessor |
| Delete the last node | O(n) | even with a tail pointer — the new tail (the predecessor) must be found |
| Search (sorted or unsorted) | O(n) | no binary search: the middle cannot be reached in O(1) |
| Length | O(n) | O(1) if a count is kept, e.g. in a header node |
N->next = P->next; first and P->next = N; second. Doing it the other way round makes P point to N and then N point to itself — every node after P is lost (a memory leak and a corrupted list).Iterative reversal walks the list once with three pointers. prev is the already-reversed part, cur the node being processed and next a bookmark for the rest of the list. For each node: save next = cur->next, turn the arrow back with cur->next = prev, then advance prev = cur and cur = next. When cur becomes NULL, prev is the new head. Time O(n), extra space O(1).
| Iteration | next saved | Reversed part (from prev) | Remaining (from cur) |
|---|---|---|---|
| start | — | empty (prev = NULL) | 10 → 20 → 30 → 40 |
| 1 | 20 | 10 → NULL | 20 → 30 → 40 |
| 2 | 30 | 20 → 10 → NULL | 30 → 40 |
| 3 | 40 | 30 → 20 → 10 → NULL | 40 |
| 4 | NULL | 40 → 30 → 20 → 10 → NULL | empty — head = prev = 40 |
Detecting a loop — Floyd's tortoise and hare. A corrupted list may have its last node pointing back into the middle. Move slow one node and fast two nodes per step. Without a loop, fast reaches NULL. With a loop, both pointers end up circling it and fast gains exactly one node per step on slow, so it cannot jump over it — they must meet. To find where the loop begins, move one pointer back to the head and advance both one node at a time; they meet at the loop's first node. Time O(n), space O(1) (a hash set of visited addresses would need O(n) space).
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
struct Node *push(struct Node *head, int v) { /* insert at front */
struct Node *p = malloc(sizeof *p);
if (!p) exit(1);
p->data = v; p->next = head;
return p;
}
struct Node *reverse(struct Node *head) { /* O(n) time, O(1) space */
struct Node *prev = NULL, *cur = head, *next;
while (cur != NULL) {
next = cur->next; /* bookmark the rest */
cur->next = prev; /* turn the arrow back */
prev = cur;
cur = next;
}
return prev; /* new head */
}
struct Node *merge(struct Node *a, struct Node *b) { /* both ascending: O(m + n) */
struct Node dummy = {0, NULL}, *tail = &dummy;
while (a != NULL && b != NULL) {
if (a->data <= b->data) { tail->next = a; a = a->next; }
else { tail->next = b; b = b->next; }
tail = tail->next;
}
tail->next = (a != NULL) ? a : b; /* attach the leftover part */
return dummy.next;
}
struct Node *middle(struct Node *head) { /* second middle if length is even */
struct Node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; }
return slow;
}
struct Node *loopStart(struct Node *head) { /* Floyd: NULL if there is no loop */
struct Node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) { /* met inside the loop */
slow = head;
while (slow != fast) { slow = slow->next; fast = fast->next; }
return slow; /* first node of the loop */
}
}
return NULL;
}
void print(struct Node *h) { for (; h; h = h->next) printf("%d ", h->data); printf("\n"); }
int main(void) {
struct Node *a = NULL, *b = NULL;
for (int v = 4; v >= 1; v--) a = push(a, v * 10); /* a: 10 20 30 40 */
a = reverse(a);
print(a); /* 40 30 20 10 */
a = reverse(a); /* back to 10 20 30 40 */
int bv[] = {35, 25, 15, 5};
for (int i = 0; i < 4; i++) b = push(b, bv[i]); /* b: 5 15 25 35 */
struct Node *m = merge(a, b);
print(m); /* 5 10 15 20 25 30 35 40 */
printf("middle = %d\n", middle(m)->data); /* 25 */
struct Node *last = m;
while (last->next) last = last->next;
last->next = m->next->next; /* corrupt: 40 now points to 15 */
printf("loop starts at %d\n", loopStart(m)->data); /* 15 */
return 0;
}Merging two sorted lists is the linked-list heart of merge sort: compare the two front nodes, move the smaller to the result, and when one list runs out attach the other in one step. At most m + n − 1 comparisons are needed and no node is copied — only links change. The middle node is found in one pass with the same slow/fast idea: when fast reaches the end, slow is halfway.
In a doubly linked list (DLL) each node has two links: prev to its predecessor and next to its successor. The first node's prev and the last node's next are NULL. The list can be traversed in both directions, and — the decisive advantage — a node can be deleted in O(1) given only a pointer to it, because its predecessor is stored inside it.
#include <stdio.h>
#include <stdlib.h>
struct DNode { int data; struct DNode *prev, *next; };
struct DNode *newDNode(int v) {
struct DNode *p = malloc(sizeof *p);
if (!p) exit(1);
p->data = v; p->prev = p->next = NULL;
return p;
}
void insertAfter(struct DNode *p, int v) { /* four link changes, O(1) */
struct DNode *q = newDNode(v);
q->prev = p; /* 1 */
q->next = p->next; /* 2 */
if (p->next != NULL) p->next->prev = q; /* 3 */
p->next = q; /* 4 */
}
void deleteNode(struct DNode **head, struct DNode *p) { /* O(1): p->prev is known */
if (p->prev != NULL) p->prev->next = p->next; else *head = p->next;
if (p->next != NULL) p->next->prev = p->prev;
free(p);
}
int main(void) {
struct DNode *head = newDNode(10);
insertAfter(head, 30);
insertAfter(head, 20); /* 10 <-> 20 <-> 30 */
deleteNode(&head, head->next); /* remove 20 */
struct DNode *t = head;
while (t->next) { printf("%d ", t->data); t = t->next; }
printf("%d | backwards:", t->data);
for (; t; t = t->prev) printf(" %d", t->data);
printf("\n"); /* 10 30 | backwards: 30 10 */
return 0;
}In a circular singly linked list the last node points back to the first instead of to NULL, so every node has a successor and any node can serve as a starting point. It is convenient to keep a pointer to the last node: then tail->next is the head, and both insertion at the front and insertion at the end take O(1). Because no link is ever NULL, traversal must stop when it returns to the starting node — the test while (p != NULL) loops forever, which is why PSC calls the circular list the one that ‘suffers from infinite traversal’.
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
struct Node *insertEnd(struct Node *tail, int v) { /* returns the new tail, O(1) */
struct Node *p = malloc(sizeof *p);
if (!p) exit(1);
p->data = v;
if (tail == NULL) { p->next = p; return p; } /* lone node points to itself */
p->next = tail->next; /* new node points to the head */
tail->next = p; /* old tail points to new node */
return p; /* (for insertFront, return tail instead) */
}
void traverse(struct Node *tail) {
if (tail == NULL) return;
struct Node *p = tail->next; /* start at the head */
do {
printf("%d ", p->data);
p = p->next;
} while (p != tail->next); /* stop when back at the head */
printf("\n");
}
int main(void) {
struct Node *tail = NULL;
for (int v = 1; v <= 4; v++) tail = insertEnd(tail, v);
traverse(tail); /* 1 2 3 4 */
return 0;
}A circular doubly linked list links the last node's next to the first node and the first node's prev to the last, giving O(1) access to both ends from a single pointer. A header linked list begins with a special header node that stores no list element (it may store the count or other metadata). In a grounded header list the last node points to NULL; in a circular header list it points back to the header. Since every data node now has a predecessor, insertions and deletions at the front need no special case, and the empty list is header->next == NULL (grounded) or header->next == header (circular).
| Variant | Last node points to | Traversal | Typical use |
|---|---|---|---|
| Singly linked | NULL | forward only | simple stacks, hash chains, adjacency lists |
| Doubly linked | NULL (and first's prev = NULL) | both ways | deques, undo/redo, LRU caches |
| Circular singly | the first node | forward, from any node | round-robin scheduling, Josephus problem, turn-taking |
| Circular doubly | the first node (first's prev = last) | both ways, endless | music playlists, buffer rings |
| Grounded header | NULL; header precedes data | start at header->next | lists that store their length in the header |
| Circular header | the header node | stop when back at header | polynomials and sparse matrices in Horowitz–Sahni |
| Feature | Array | Linked list |
|---|---|---|
| Memory layout | one contiguous block | nodes scattered anywhere in the heap |
| Size | fixed at allocation (resizing means copying) | grows and shrinks one node at a time |
| Access to the k-th element | O(1) random access: base + k × size | O(k) sequential access only |
| Search in sorted data | binary search, O(log n) | O(n) — no O(1) jump to the middle |
| Insert/delete at the front | O(n) — shift every element | O(1) |
| Insert/delete in the middle | O(n) shifting | O(1) once the node is reached (O(n) to reach it) |
| Insert at the end | O(1) if there is spare capacity | O(n), or O(1) with a tail pointer |
| Memory overhead | none per element, but unused capacity is wasted | one pointer per node (two in a DLL) |
| Cache behaviour | excellent locality | poor locality — pointer chasing |
| Best for | static data, frequent indexing, binary search | frequent insertions/deletions, unknown size |
Polynomials. Store one node per non-zero term — (coefficient, exponent, next) — in decreasing order of exponent. Adding two polynomials is a merge: if one exponent is larger, copy that term; if the exponents are equal, add the coefficients and keep the term only when the sum is non-zero. Each term of each input is visited once, so addition costs O(m + n) for m and n terms. Multiplication multiplies every pair of terms, O(m·n), and combines like terms.
#include <stdio.h>
#include <stdlib.h>
struct Term { int coeff, exp; struct Term *next; };
struct Term *append(struct Term *tail, int c, int e) { /* returns the new tail */
struct Term *t = malloc(sizeof *t);
if (!t) exit(1);
t->coeff = c; t->exp = e; t->next = NULL;
if (tail) tail->next = t;
return t;
}
struct Term *addPoly(struct Term *p, struct Term *q) { /* both sorted by falling exponent */
struct Term head = {0, 0, NULL}, *tail = &head;
while (p && q) {
if (p->exp > q->exp) { tail = append(tail, p->coeff, p->exp); p = p->next; }
else if (p->exp < q->exp) { tail = append(tail, q->coeff, q->exp); q = q->next; }
else { /* like terms */
int c = p->coeff + q->coeff;
if (c != 0) tail = append(tail, c, p->exp); /* drop zero terms */
p = p->next; q = q->next;
}
}
for (; p; p = p->next) tail = append(tail, p->coeff, p->exp);
for (; q; q = q->next) tail = append(tail, q->coeff, q->exp);
return head.next;
}
void show(struct Term *t) {
for (; t; t = t->next) printf("%+dx^%d ", t->coeff, t->exp);
printf("\n");
}
int main(void) {
struct Term *p, *q, *t;
p = t = append(NULL, 3, 4); t = append(t, 2, 2); t = append(t, -5, 0);
q = t = append(NULL, 4, 3); t = append(t, -2, 2); t = append(t, 1, 1); t = append(t, 8, 0);
show(addPoly(p, q)); /* +3x^4 +4x^3 +1x^1 +3x^0 */
return 0;
}Sparse matrices. A matrix in which most elements are zero is sparse. Storing it as a full 2-D array wastes memory on zeros, so we store only the non-zero entries. The triplet representation keeps (row, column, value) for each non-zero element; the linked version chains these triplets as nodes. Horowitz–Sahni's orthogonal list goes further: each non-zero node is linked into both its row list and its column list (right and down pointers), with header nodes for every row and column, so whole rows or columns can be walked quickly.
| Row | Col 0 | Col 1 | Col 2 | Col 3 | Col 4 | Triplet nodes for this row |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 3 | 0 | 0 | (0, 2, 3) |
| 1 | 0 | 0 | 0 | 0 | 7 | (1, 4, 7) |
| 2 | 0 | 0 | 0 | 0 | 0 | — |
| 3 | 0 | 2 | 0 | 6 | 0 | (3, 1, 2) → (3, 3, 6) |
Try the problem first, then reveal the working one step at a time.
Add P(x) = 3x⁴ + 2x² − 5 and Q(x) = 4x³ − 2x² + x + 8, both stored as linked lists of (coefficient, exponent) nodes in decreasing order of exponent.
The list is 1 → 2 → 3 → 4 → 5 → 6, and node 6 wrongly points back to node 3. Trace the tortoise-and-hare algorithm, find where the loop starts and its length.
For the list 1 → 2 → 3 → 4 → 5, what does fun(head) print? void fun(struct Node *h) { if (h == NULL) return; printf("%d ", h->data); if (h->next != NULL) fun(h->next->next); printf("%d ", h->data); }
You are given a pointer p to some node of a singly linked list but not the head pointer. Delete that node. When does the method fail?
Write a recursive C function int count(struct Node *h) that returns the number of nodes. State its time and space complexity.
In a doubly linked list, give the pointer assignments that insert a new node N immediately before node P (P is not the first node).
Merge the sorted lists 2 → 5 → 9 and 1 → 6 → 7 → 12 into one sorted list. How many key comparisons are made?
With the loop while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; } (both starting at the head), which node does slow end on for the lists 1 → … → 7 and 1 → … → 6?
Josephus problem: 7 people numbered 1–7 stand in a circle. Counting starts at person 1 and every 3rd person is eliminated until one remains. Who survives, and why is a circular linked list the natural model?
P->next = N first) loses the rest of the list.while (p != NULL) never ends; stop when you come back to the starting node.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
struct Node { int data; struct Node *next; }; is an example of a:Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.