Linked lists
A linked list is a linear data structure of nodes linked via pointers or references, allowing dynamic size and easy insertion or deletion without shifting elements.
Theory & Explanation
Linked Lists and Polynomial Arithmetic
Exam Note: A linked list is a dynamic linear data structure made up of separate elements called nodes. Unlike an array, nodes do not need contiguous memory locations; instead, each node holds data and a link (pointer or index) to the next node. This makes linked lists flexible for frequent insertions and deletions without shifting large blocks of data.
1. Singly Linked List: Array vs. Pointer Implementation
A singly linked list is a sequence of nodes where each node contains a data field and a single link pointing to the next node. The list starts at a reference called head (or start), and the last node points to NULL (or -1 in an array representation) to mark the end of the list.
Pointer Implementation of a Singly Linked List
In pointer implementation, each node is allocated dynamically on the heap using malloc() and contains a data value plus a pointer (struct Node next) to the next node. Memory grows or shrinks node by node as needed, avoiding wasted pre-allocated space.
Array Implementation of a Singly Linked List
In array implementation (static/cursor-style representation), parallel arrays—such as data[] for values and next[] for storing the index of the next node—simulates links using array indices instead of memory pointers, alongside a head index and a free-slot tracker. It is useful in environments without dynamic pointers or when a fixed maximum pool size is known in advance.
| Feature | Pointer Implementation | Array Implementation |
|---|---|---|
| Link Mechanism | Uses pointers (struct Node next) to store memory addresses. |
Uses integer indices (next[i]) inside parallel arrays. |
| Memory Allocation | Dynamic (allocated per node at runtime via malloc). |
Static capacity fixed at compile/creation time. |
| Memory Overhead | Extra pointer per node; no unused slots beyond allocated nodes. | May waste unused slots if capacity is overestimated; fails if full. |
| End Marker | NULL pointer in the last node. |
-1 (typically) in the next index array. |
C Program — Array and Pointer Implementations of a Singly Linked List:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 10
/ --- 1. Pointer-based Node --- /
struct PtrNode {
int data;
struct PtrNode next;
};
struct PtrNode ptr_insert_front(struct PtrNode head, int val) {
struct PtrNode new_node = (struct PtrNode )malloc(sizeof(struct PtrNode));
new_node->data = val;
new_node->next = head;
return new_node;
}
void ptr_traverse(struct PtrNode head) {
struct PtrNode curr = head;
while (curr != NULL) {
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("NULL\n");
}
/ --- 2. Array-based Singly Linked List --- /
struct ArraySLL {
int data[MAX_NODES];
int next[MAX_NODES];
int head;
int free_idx;
};
void arr_init(struct ArraySLL list) {
list->head = -1;
list->free_idx = 0;
for (int i = 0; i < MAX_NODES - 1; i++) {
list->next[i] = i + 1;
}
list->next[MAX_NODES - 1] = -1;
}
void arr_insert_front(struct ArraySLL list, int val) {
if (list->free_idx == -1) {
printf("List full\n");
return;
}
int idx = list->free_idx;
list->free_idx = list->next[idx];
list->data[idx] = val;
list->next[idx] = list->head;
list->head = idx;
}
void arr_traverse(struct ArraySLL list) {
int curr = list->head;
while (curr != -1) {
printf("%d -> ", list->data[curr]);
curr = list->next[curr];
}
printf("END\n");
}
int main(void) {
struct PtrNode head = NULL;
head = ptr_insert_front(head, 30);
head = ptr_insert_front(head, 20);
head = ptr_insert_front(head, 10);
printf("Pointer SLL: ");
ptr_traverse(head);
struct ArraySLL alist;
arr_init(&alist);
arr_insert_front(&alist, 30);
arr_insert_front(&alist, 20);
arr_insert_front(&alist, 10);
printf("Array SLL: ");
arr_traverse(&alist);
return 0;
}
Expected Output:
Pointer SLL: 10 -> 20 -> 30 -> NULL
Array SLL: 10 -> 20 -> 30 -> END
2. Doubly Linked List
A doubly linked list (DLL) is a linked list in which each node has three fields: prev (pointer to the previous node), data (stored value), and next (pointer to the next node). For the first node, prev is NULL; for the last node, next is NULL.
- Two-way traversal: You can move forward using
nextand backward usingprev. - Easier deletion of a given node: Because a node stores its
prevpointer, updating neighbors does not always require scanning fromheadto find the predecessor. - Extra memory cost: Each node stores one additional pointer compared to a singly linked list, and pointer updates require extra care during insertion and deletion.
3. Circularly Linked List
A circularly linked list is a variation where the last node links back to the first node instead of NULL, forming a closed loop. It can be singly circular (last node's next points to head) or doubly circular (last node's next points to head and head->prev points to the last node).
- Continuous cycling: From any node, you can reach every other node in the list by following links.
- Stopping condition in traversal: Instead of checking for
NULL, traversal stops when it returns to the starting node (taking care when the list is empty or has a single node). - Common uses: Round-robin CPU scheduling, multiplayer turn rotation, and circular buffers.
4. Operations on a Linked List: Insertion, Deletion, and Traversal
For exam answers, explain each operation clearly for the beginning, end, and middle/specific position, and mention boundary cases such as an empty list or single-node list.
A. Traversal
Start a temporary pointer temp = head. In a singly linked list, while temp != NULL, visit/print temp->data and advance temp = temp->next. Traversal visits every node once, taking O(n) time and O(1) extra space.
B. Insertion
- At the beginning: Create a new node, set
new_node->next = head, and updatehead = new_node. Time:O(1). - At the end: Create a new node with
next = NULL. If the list is empty, sethead = new_node; otherwise traverse to the last node and setlast->next = new_node. Time:O(n)without a tail pointer (O(1)with a tail pointer). - At a given position / after a node: Traverse to the target position or predecessor node, link
new_node->next = prev->next, and setprev->next = new_node. Time:O(n)in the worst case.
C. Deletion
- From the beginning: If
head == NULL, report underflow/empty list. Otherwise storetemp = head, sethead = head->next, andfree(temp). Time:O(1). - From the end: If the list has one node, free
headand sethead = NULL. Otherwise traverse to the second-last node, free itsnextnode, and setsecond_last->next = NULL. Time:O(n). - By value or position: Find the target node while tracking its previous node, link
prev->next = curr->next, andfree(curr). Time:O(n)in the worst case.
C Program — Singly Linked List Insertion, Deletion, and Traversal:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node next;
};
struct Node create_node(int val) {
struct Node n = (struct Node )malloc(sizeof(struct Node));
n->data = val;
n->next = NULL;
return n;
}
struct Node insert_beginning(struct Node head, int val) {
struct Node n = create_node(val);
n->next = head;
return n;
}
struct Node insert_end(struct Node head, int val) {
struct Node n = create_node(val);
if (head == NULL) {
return n;
}
struct Node curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
return head;
}
struct Node delete_value(struct Node head, int key) {
if (head == NULL) {
return NULL;
}
struct Node curr = head, prev = NULL;
if (curr->data == key) {
head = curr->next;
free(curr);
return head;
}
while (curr != NULL && curr->data != key) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
prev->next = curr->next;
free(curr);
}
return head;
}
void traverse(struct Node head) {
struct Node curr = head;
while (curr != NULL) {
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("NULL\n");
}
int main(void) {
struct Node head = NULL;
head = insert_end(head, 10);
head = insert_end(head, 20);
head = insert_beginning(head, 5);
head = insert_end(head, 30);
printf("After insertions: ");
traverse(head);
head = delete_value(head, 20);
printf("After deleting 20: ");
traverse(head);
return 0;
}
Expected Output:
After insertions: 5 -> 10 -> 20 -> 30 -> NULL
After deleting 20: 5 -> 10 -> 30 -> NULL
5. Polynomial Representation and Operations (Single & Two Variables)
A linked list is ideal for representing sparse polynomials (polynomials with many zero coefficients) because we only store non-zero terms. Each node stores a coefficient, the exponent(s), and a next pointer, typically kept in descending order of degree/exponents.
A. Single-Variable Polynomial
A single-variable polynomial in x, such as P(x) = 4x3 + 3x2 + 5, is represented where each node stores coeff, exp (power of x), and next.
- Addition and Subtraction: Walk through both sorted lists together. If exponents match, add (or subtract) coefficients; if the sum/difference is non-zero, create a result node. If one exponent is larger, copy that term and advance that list.
- Multiplication: Multiply every term of polynomial 1 with every term of polynomial 2 (
coeff = c1 c2,exp = e1 + e2), insert into the result list, and combine like terms that share the same exponent.
B. Two-Variable Polynomial
A two-variable polynomial in x and y, such as Q(x, y) = 3x2y + 2xy2 + 4, can be represented using nodes containing coeff, exp_x (power of x), exp_y (power of y), and next.
- Addition and Subtraction: Terms are combined only when both
exp_xandexp_ymatch (p1->exp_x == p2->exp_x && p1->exp_y == p2->exp_y). Otherwise, each distinct term is placed in the result according to a consistent ordering (for example, higherexp_xfirst, then higherexp_y). - Multiplication: For each term of the first polynomial and each term of the second polynomial, multiply coefficients (
c1 c2) and add exponents separately for each variable (new_exp_x = px1 + px2andnew_exp_y = py1 + py2), then combine terms with identical(exp_x, exp_y)pairs.
C Program — Single-Variable Polynomial Addition, Subtraction, and Multiplication:
#include <stdio.h>
#include <stdlib.h>
struct Poly1D {
int coeff;
int exp;
struct Poly1D next;
};
struct Poly1D insert_term_1d(struct Poly1D head, int coeff, int exp) {
if (coeff == 0) {
return head;
}
struct Poly1D curr = head, prev = NULL;
while (curr != NULL && curr->exp > exp) {
prev = curr;
curr = curr->next;
}
if (curr != NULL && curr->exp == exp) {
curr->coeff += coeff;
if (curr->coeff == 0) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
}
return head;
}
struct Poly1D n = (struct Poly1D )malloc(sizeof(struct Poly1D));
n->coeff = coeff;
n->exp = exp;
n->next = curr;
if (prev == NULL) {
head = n;
} else {
prev->next = n;
}
return head;
}
struct Poly1D add_sub_1d(struct Poly1D p1, struct Poly1D p2, int sign) {
struct Poly1D res = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->exp == p2->exp) {
res = insert_term_1d(res, p1->coeff + sign p2->coeff, p1->exp);
p1 = p1->next;
p2 = p2->next;
} else if (p1->exp > p2->exp) {
res = insert_term_1d(res, p1->coeff, p1->exp);
p1 = p1->next;
} else {
res = insert_term_1d(res, sign p2->coeff, p2->exp);
p2 = p2->next;
}
}
while (p1 != NULL) {
res = insert_term_1d(res, p1->coeff, p1->exp);
p1 = p1->next;
}
while (p2 != NULL) {
res = insert_term_1d(res, sign p2->coeff, p2->exp);
p2 = p2->next;
}
return res;
}
struct Poly1D multiply_1d(struct Poly1D p1, struct Poly1D p2) {
struct Poly1D res = NULL;
for (struct Poly1D a = p1; a != NULL; a = a->next) {
for (struct Poly1D b = p2; b != NULL; b = b->next) {
res = insert_term_1d(res, a->coeff b->coeff, a->exp + b->exp);
}
}
return res;
}
void print_poly_1d(struct Poly1D head) {
if (head == NULL) {
printf("0\n");
return;
}
struct Poly1D curr = head;
while (curr != NULL) {
printf("%dx^%d", curr->coeff, curr->exp);
if (curr->next != NULL) {
printf(" + ");
}
curr = curr->next;
}
printf("\n");
}
int main(void) {
struct Poly1D p1 = NULL, p2 = NULL;
/ P1(x) = 3x^2 + 2x + 1 /
p1 = insert_term_1d(p1, 3, 2);
p1 = insert_term_1d(p1, 2, 1);
p1 = insert_term_1d(p1, 1, 0);
/ P2(x) = 2x^2 + 5 /
p2 = insert_term_1d(p2, 2, 2);
p2 = insert_term_1d(p2, 5, 0);
printf("P1(x) = "); print_poly_1d(p1);
printf("P2(x) = "); print_poly_1d(p2);
printf("Sum = "); print_poly_1d(add_sub_1d(p1, p2, 1));
printf("Diff = "); print_poly_1d(add_sub_1d(p1, p2, -1));
printf("Prod = "); print_poly_1d(multiply_1d(p1, p2));
return 0;
}
Expected Output (Single-Variable):
P1(x) = 3x^2 + 2x^1 + 1x^0
P2(x) = 2x^2 + 5x^0
Sum = 5x^2 + 2x^1 + 6x^0
Diff = 1x^2 + 2x^1 + -4x^0
Prod = 6x^4 + 4x^3 + 17x^2 + 10x^1 + 5x^0
C Program — Two-Variable Polynomial Addition, Subtraction, and Multiplication:
#include <stdio.h>
#include <stdlib.h>
struct Poly2D {
int coeff;
int exp_x;
int exp_y;
struct Poly2D next;
};
int compare_terms_2d(int x1, int y1, int x2, int y2) {
if (x1 != x2) {
return (x1 > x2) ? 1 : -1;
}
if (y1 != y2) {
return (y1 > y2) ? 1 : -1;
}
return 0;
}
struct Poly2D insert_term_2d(struct Poly2D head, int coeff, int ex, int ey) {
if (coeff == 0) {
return head;
}
struct Poly2D curr = head, prev = NULL;
while (curr != NULL && compare_terms_2d(curr->exp_x, curr->exp_y, ex, ey) > 0) {
prev = curr;
curr = curr->next;
}
if (curr != NULL && compare_terms_2d(curr->exp_x, curr->exp_y, ex, ey) == 0) {
curr->coeff += coeff;
if (curr->coeff == 0) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
}
return head;
}
struct Poly2D n = (struct Poly2D )malloc(sizeof(struct Poly2D));
n->coeff = coeff;
n->exp_x = ex;
n->exp_y = ey;
n->next = curr;
if (prev == NULL) {
head = n;
} else {
prev->next = n;
}
return head;
}
struct Poly2D add_sub_2d(struct Poly2D p1, struct Poly2D p2, int sign) {
struct Poly2D res = NULL;
for (struct Poly2D a = p1; a != NULL; a = a->next) {
res = insert_term_2d(res, a->coeff, a->exp_x, a->exp_y);
}
for (struct Poly2D b = p2; b != NULL; b = b->next) {
res = insert_term_2d(res, sign b->coeff, b->exp_x, b->exp_y);
}
return res;
}
struct Poly2D multiply_2d(struct Poly2D p1, struct Poly2D p2) {
struct Poly2D res = NULL;
for (struct Poly2D a = p1; a != NULL; a = a->next) {
for (struct Poly2D b = p2; b != NULL; b = b->next) {
res = insert_term_2d(res, a->coeff b->coeff, a->exp_x + b->exp_x, a->exp_y + b->exp_y);
}
}
return res;
}
void print_poly_2d(struct Poly2D head) {
if (head == NULL) {
printf("0\n");
return;
}
struct Poly2D curr = head;
while (curr != NULL) {
printf("%dx^%dy^%d", curr->coeff, curr->exp_x, curr->exp_y);
if (curr->next != NULL) {
printf(" + ");
}
curr = curr->next;
}
printf("\n");
}
int main(void) {
struct Poly2D p1 = NULL, p2 = NULL;
/ P1(x, y) = 2x^1y^1 + 3x^0y^0 /
p1 = insert_term_2d(p1, 2, 1, 1);
p1 = insert_term_2d(p1, 3, 0, 0);
/ P2(x, y) = 4x^1y^1 + 1x^0y^0 */
p2 = insert_term_2d(p2, 4, 1, 1);
p2 = insert_term_2d(p2, 1, 0, 0);
printf("P1(x,y) = "); print_poly_2d(p1);
printf("P2(x,y) = "); print_poly_2d(p2);
printf("Sum = "); print_poly_2d(add_sub_2d(p1, p2, 1));
printf("Diff = "); print_poly_2d(add_sub_2d(p1, p2, -1));
printf("Prod = "); print_poly_2d(multiply_2d(p1, p2));
return 0;
}
Expected Output (Two-Variable):
P1(x,y) = 2x^1y^1 + 3x^0y^0
P2(x,y) = 4x^1y^1 + 1x^0y^0
Sum = 6x^1y^1 + 4x^0y^0
Diff = -2x^1y^1 + 2x^0y^0
Prod = 8x^2y^2 + 14x^1y^1 + 3x^0y^0
