Introduction to Data Structures Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Data Structures, Arrays, Searching & Sorting
Module 2
Linked Lists
Module 3
Stack & Queue
Module 4
Trees & Binary Search Trees
Module 5
Graphs & Flexi Module Extensions
Read Module Notes Online
Module I: Introduction to Data Structures, Arrays, Searching & Sorting
Chapter 1: Foundations and Classification of Data Structures
1.1 Definition, Abstraction, and Role of Data Structures
A data structure is a systematic, formal mechanism for organizing, storing, and managing data in computer memory so that retrieval, insertion, deletion, modification, and aggregation operations execute efficiently. Whereas a primitive data type (such as int, char, float, or double) represents a single atomic value, a data structure establishes both logical and physical relationships among a collection of data elements. The choice of data structure directly governs the asymptotic time complexity and memory footprint of an algorithm.
In software engineering, a data structure is separated into two conceptual layers: the Abstract Data Type (ADT) and its concrete implementation. An ADT defines a mathematical model of the data together with the set of valid operations and their behavioral specifications, independent of any programming language or memory layout. For instance, a List ADT specifies operations such as get(i), insert(i, x), and remove(i). The concrete data structure—whether a contiguous array or a pointer-linked chain of nodes—provides the actual in-memory representation and algorithms that satisfy the ADT contract.
Using ADTs promotes modularity and information hiding: client code interacts exclusively with the public operation interface, allowing engineers to replace an underlying array implementation with a linked or tree-based implementation without rewriting application logic.
1.2 Classification of Data Structures
Data structures are systematically classified along two orthogonal dimensions: structural organization (Linear versus Non-Linear) and memory allocation strategy (Static versus Dynamic).
- Linear Data Structures: Elements are arranged in a sequential, one-dimensional logical order such that every element (except the first and the last) possesses a unique predecessor and a unique successor. Traversal proceeds along a single level from start to finish. Canonical examples include Arrays, Singly Linked Lists, Doubly Linked Lists, Stacks, and Queues.
- Non-Linear Data Structures: Elements are organized hierarchically (parent-child) or as an interconnected network (many-to-many) rather than a single linear sequence. A single element may connect to zero, one, or multiple other elements across different levels. Canonical examples include General Trees, Binary Trees, Binary Search Trees, Heaps, and Graphs.
- Static Data Structures: Memory capacity and layout are fixed at compile time or at the moment of allocation. Because the size cannot grow or shrink dynamically during program execution, static structures provide constant-time direct indexing but risk either memory wastage (if over-allocated) or overflow errors (if under-allocated). The standard fixed-size C array is the primary example.
- Dynamic Data Structures: Memory is allocated and reclaimed incrementally from the system heap at runtime. The structure expands when new elements are inserted and contracts when elements are deleted, matching memory consumption to the actual data volume at the cost of pointer storage overhead. Linked lists, linked stacks, linked queues, and dynamically allocated trees are dynamic structures.
| Classification Dimension | Category | Structural Characteristic | Memory Behavior | Representative Examples |
|---|---|---|---|---|
| Organization | Linear | Sequential; unique predecessor and successor | Contiguous or pointer-chained | Array, Linked List, Stack, Queue |
| Organization | Non-Linear | Hierarchical or network; multi-level links | Tree/graph node pointers or matrices | Binary Tree, BST, AVL Tree, Graph |
| Allocation | Static | Fixed capacity determined at allocation | Contiguous stack/global/fixed block | Static 1D Array, Fixed 2D Matrix |
| Allocation | Dynamic | Variable capacity; grows and shrinks at runtime | Heap allocation via malloc/free |
Singly/Doubly Linked List, Linked Tree |
1.3 Fundamental Operations and Real-World Applications
Across both linear and non-linear categories, software systems rely on six core data structure operations:
- Traversing: Accessing and processing each element in the structure exactly once, such as printing every record or computing an aggregate sum.
- Searching: Locating the index or memory reference of an element that satisfies a given search key.
- Inserting: Adding a new element at a specified logical position (beginning, end, arbitrary index, or sorted order).
- Deleting: Removing an existing element from the structure and either shifting remaining elements or releasing its heap node.
- Sorting: Rearranging elements into a prescribed order, such as ascending numerical or alphabetical sequence.
- Merging: Combining two separately maintained collections (typically sorted arrays or lists) into a single unified collection.
Applications of data structures span every domain of computer science. Operating systems use priority queues and circular queues for CPU scheduling and I/O buffering, and stacks for managing function call frames. Relational database management systems rely on B-trees and B+ trees to index millions of disk records in logarithmic time. Compilers build expression trees and symbol tables to parse and optimize source code. Mapping services, social networks, and telecommunications routers model road intersections, user relationships, and packet switches as weighted graphs.
Chapter 2: Single-Dimensional Arrays and Memory Representation
2.1 Concept and Contiguous Memory Model
A single-dimensional array is a finite, ordered collection of homogeneous elements stored in contiguous memory addresses. Because all elements share an identical data type and byte width, the system can compute the exact physical address of any element A[i] in constant time without scanning preceding elements. Let represent the base address (the starting address of the first element in memory), represent the byte size of each element, and represent the lower bound index ( in C, C++, and Java; in 1-based mathematical notation).
int); = target element index; = lower bound index (0 in C).
Worked Numerical Example 1: Suppose an integer array A[10] begins at base address , with bytes per element and . The physical address of A[6] is . If the array uses 1-based indexing (), the address of A[6] would be . Similarly, for a double array () indexed from to starting at , the address of element at index is .
2.2 Array Operations: Traversal, Insertion, Deletion, and Merging
Traversal iterates an index variable from to , accessing each element in total time. Insertion at a target index (where and ) requires preserving existing elements by shifting elements at indices one slot to the right, writing the new value into arr[pos], and incrementing the active count . Deletion at index (where ) removes the element by shifting elements at indices one slot to the left and decrementing . In the worst case (inserting or deleting at index 0), shifts occur, yielding time complexity; at the end of the array, zero shifts occur, yielding time.
Merging combines two sorted arrays A[0..n1-1] and B[0..n2-1] into a third sorted array C[0..n1+n2-1] in time using two read pointers i and j and one write pointer k. At each step, the smaller of A[i] and B[j] is copied to C[k], and any remaining tail elements are copied once one input array is exhausted.
#include <stdio.h>
#define MAX 100
void traverseArray(const int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int insertAt(int arr[], int *n, int pos, int val) {
if (*n >= MAX || pos < 0 || pos > *n) return 0;
for (int i = *n - 1; i >= pos; i--) {
arr[i + 1] = arr[i];
}
arr[pos] = val;
(*n)++;
return 1;
}
int deleteAt(int arr[], int *n, int pos) {
if (*n <= 0 || pos < 0 || pos >= *n) return 0;
for (int i = pos; i < *n - 1; i++) {
arr[i] = arr[i + 1];
}
(*n)--;
return 1;
}
void mergeSorted(const int A[], int n1, const int B[], int n2, int C[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (A[i] <= B[j]) C[k++] = A[i++];
else C[k++] = B[j++];
}
while (i < n1) C[k++] = A[i++];
while (j < n2) C[k++] = B[j++];
}Chapter 3: Searching Algorithms
3.1 Linear Search (Sequential Search)
Linear search scans an array sequentially from index to , comparing each element against the target key. Because it does not rely on any ordering relationship among elements, linear search works on both sorted and unsorted datasets, as well as on linked lists where random access is unavailable. When the target is found at index , the algorithm immediately returns ; if the loop reaches the end without a match, it returns -1.
Complexity Analysis: In the best case, the key sits at index 0, requiring 1 comparison (). In the worst case (key at index or absent), comparisons are executed (). For a uniformly distributed successful search, the average number of comparisons is , which is . Auxiliary space is .
3.2 Binary Search
Binary search is a divide-and-conquer search algorithm applicable exclusively to sorted arrays (or random-access sorted sequences). It maintains two boundary indices, low (initially 0) and high (initially ), and computes the midpoint mid = low + (high - low) / 2 (preferred over (low + high) / 2 to prevent signed integer overflow on large indices). At each iteration, three outcomes are possible:
- If
arr[mid] == key, the target is located andmidis returned. - If
key < arr[mid], all elements frommidtohighare strictly greater thankey(assuming ascending order), so the search narrows to the left half viahigh = mid - 1. - If
key > arr[mid], all elements fromlowtomidare strictly smaller thankey, so the search narrows to the right half vialow = mid + 1.
Because each comparison eliminates half of the remaining candidate range, after iterations at most elements remain. Setting yields . Thus, binary search achieves worst-case and average-case time complexity, with best-case time (when the initial midpoint matches) and auxiliary space in iterative form (or call-stack space in recursive form). For an array of 1,000,000 sorted elements, binary search requires at most 20 comparisons, whereas linear search may require up to 1,000,000 comparisons.
| Step | low | high | mid | arr[mid] | Comparison with key = 38 (Array: [5, 11, 16, 22, 27, 38, 42, 55, 70]) |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 27 | 38 > 27 → set low = 5 |
| 2 | 5 | 8 | 6 | 42 | 38 < 42 → set high = 5 |
| 3 | 5 | 5 | 5 | 38 | 38 == 38 → Found at index 5 |
int linearSearch(const int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) return i;
}
return -1;
}
int binarySearchIterative(const int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
if (key < arr[mid]) high = mid - 1;
else low = mid + 1;
}
return -1;
}
int binarySearchRecursive(const int arr[], int low, int high, int key) {
if (low > high) return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
if (key < arr[mid]) return binarySearchRecursive(arr, low, mid - 1, key);
return binarySearchRecursive(arr, mid + 1, high, key);
}3.3 Linear Search versus Binary Search
| Feature | Linear Search | Binary Search |
|---|---|---|
| Prerequisite | None (works on unsorted data) | Array must be sorted |
| Access Pattern | Sequential | Random access (midpoint halving) |
| Time Complexity (Worst) | ||
| Linked List Suitability | Suitable | Inefficient ( to find midpoint) |
Chapter 4: Elementary Sorting Algorithms and Complexity Analysis
4.1 Bubble Sort
Bubble sort repeatedly traverses the unsorted portion of the array, comparing adjacent pairs arr[j] and arr[j + 1] and swapping them whenever arr[j] > arr[j + 1]. In each pass, the largest remaining element "bubbles" rightward into its final sorted position at the end of the unsorted segment. After passes, the rightmost elements are guaranteed to be sorted, so the inner loop bound shrinks to .
An important optimization introduces a swapped flag initialized to 0 before each pass. If an entire pass completes with swapped == 0, the array is already sorted and the algorithm terminates early. With this flag, best-case complexity on an already-sorted input drops to (1 pass of comparisons). Worst-case (reverse-sorted input) and average-case complexities are , performing comparisons. Bubble sort is stable and in-place ( extra space).
4.2 Selection Sort
Selection sort divides the array into a sorted left prefix arr[0..i-1] and an unsorted right suffix arr[i..n-1]. In each outer iteration from to , it scans the unsorted suffix to identify the index minIdx of the smallest element and swaps arr[i] with arr[minIdx]. Because it performs at most one swap per outer iteration, selection sort executes at most swaps overall, minimizing memory write operations (useful for flash memory or EEPROM). However, it always performs comparisons regardless of input order, so best, average, and worst cases are all . Standard selection sort is not stable because long-distance swaps can reorder equal keys.
4.3 Insertion Sort
Insertion sort constructs the final sorted array one element at a time, analogous to sorting playing cards in hand. Starting at index , it saves key = arr[i] and scans backward through the already-sorted prefix arr[0..i-1], shifting every element strictly greater than key one slot to the right. Once an element less than or equal to key (or index -1) is reached, key is placed into the vacated slot arr[j + 1].
Insertion sort is adaptive (runs in on already-sorted or nearly-sorted data because the inner while loop terminates immediately), stable (strict > comparison preserves relative order of equal keys), and in-place ( auxiliary space). In the worst case (reverse-sorted input), it performs shifts, yielding time. For small arrays (), insertion sort often outperforms asymptotically faster algorithms due to tiny constant factors and cache locality.
| Input Array | Bubble Sort (Pass Result) | Selection Sort (Pass Result) | Insertion Sort (Step Result) |
|---|---|---|---|
Initial: [29, 10, 14, 37, 13] | Pass 1: [10, 14, 29, 13, 37] | Pass 1: [10, 29, 14, 37, 13] | i=1: [10, 29, 14, 37, 13] |
| Step 2 | Pass 2: [10, 14, 13, 29, 37] | Pass 2: [10, 13, 14, 37, 29] | i=2: [10, 14, 29, 37, 13] |
| Step 3 | Pass 3: [10, 13, 14, 29, 37] | Pass 3: [10, 13, 14, 37, 29] | i=3: [10, 14, 29, 37, 13] |
| Final Sorted | Pass 4: [10, 13, 14, 29, 37] | Pass 4: [10, 13, 14, 29, 37] | i=4: [10, 13, 14, 29, 37] |
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int swapped = 0;
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp;
swapped = 1;
}
}
if (!swapped) break;
}
}
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
if (minIdx != i) {
int tmp = arr[i]; arr[i] = arr[minIdx]; arr[minIdx] = tmp;
}
}
}
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i], j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}4.4 Time and Space Complexity Analysis
Time complexity expresses the growth of elementary operations as a function of input size , while space complexity quantifies total memory used—comprising fixed space (code, constants, simple variables) and variable/auxiliary space (dynamically allocated structures and recursion call-stack frames). Asymptotic notations capture growth rates as :
- Big-O Notation : Asymptotic upper bound. if there exist positive constants and such that for all . Used predominantly for worst-case guarantees.
- Omega Notation : Asymptotic lower bound. if for all .
- Theta Notation : Asymptotic tight bound. if for all .
Standard complexity classes ordered from fastest to slowest growth are: . For example, at , , , and .
| Algorithm | Best Case | Average Case | Worst Case | Auxiliary Space | Stable? |
|---|---|---|---|---|---|
| Linear Search | N/A | ||||
| Binary Search | iter. | N/A | |||
| Bubble Sort (opt.) | Yes | ||||
| Selection Sort | No | ||||
| Insertion Sort | Yes |
Chapter 5: Multidimensional Arrays and Sparse Matrices
5.1 Row-Major and Column-Major Memory Representations
Because computer RAM is addressed as a one-dimensional linear byte sequence, a two-dimensional array A[M][N] with rows and columns must be mapped onto linear memory using either Row-Major Order or Column-Major Order.
- Row-Major Order (C, C++, Java, Python): All elements of row 0 are stored contiguously, followed by row 1, row 2, and so forth up to row . To locate
A[i][j](0-based), we skip complete rows of elements each, plus elements in row . - Column-Major Order (Fortran, MATLAB, R): All elements of column 0 are stored contiguously, followed by column 1, and so forth up to column . To locate
A[i][j], we skip complete columns of elements each, plus elements down column .
Worked Numerical Example 2: Consider a 2D array A[4][5] () of 4-byte integers () starting at . For element A[2][3]: under Row-Major order, . Under Column-Major order, .
5.2 Sparse Matrix and Triplet Array Representation
A sparse matrix is a matrix in which most entries are zero (typically over two-thirds of the cells). Storing a large sparse matrix in a conventional 2D array wastes memory and forces algorithms such as matrix addition or transpose to process zero entries needlessly. The 3-tuple (triplet) array representation compacts the matrix into a 2D table of dimensions , where is the number of non-zero elements.
Row 0 serves as the metadata header storing (M, N, k): total rows, total columns, and count of non-zero elements. Rows through each store one non-zero entry as (row, col, value) in row-major order. Memory compression is achieved whenever . Transposing a sparse matrix in triplet form swaps each entry's row and column indices and re-orders entries by the new row index (the original column index).
| Triplet Row | Row Index | Column Index | Value | Meaning |
|---|---|---|---|---|
| 0 (Header) | 4 | 5 | 4 | 4x5 matrix with 4 non-zero elements |
| 1 | 0 | 2 | 15 | A[0][2] = 15 |
| 2 | 1 | 0 | 22 | A[1][0] = 22 |
| 3 | 2 | 4 | -9 | A[2][4] = -9 |
| 4 | 3 | 1 | 40 | A[3][1] = 40 |
typedef struct {
int row, col, val;
} Triplet;
int toSparseTriplet(int mat[10][10], int M, int N, Triplet sp[]) {
int k = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (mat[i][j] != 0) {
k++;
sp[k].row = i; sp[k].col = j; sp[k].val = mat[i][j];
}
}
}
sp[0].row = M; sp[0].col = N; sp[0].val = k;
return k + 1;
}
void transposeSparse(const Triplet a[], Triplet b[]) {
int rows = a[0].row, cols = a[0].col, terms = a[0].val;
b[0].row = cols; b[0].col = rows; b[0].val = terms;
int q = 1;
for (int c = 0; c < cols; c++) {
for (int i = 1; i <= terms; i++) {
if (a[i].col == c) {
b[q].row = a[i].col;
b[q].col = a[i].row;
b[q].val = a[i].val;
q++;
}
}
}
}5.3 Fast Sparse Matrix Transpose and 3D Array Addressing
While the simple transpose algorithm scans all entries once per column ( time), a fast transpose computes the exact destination index for every entry in linear time using two auxiliary arrays: rowTerms[col] (counting non-zero entries per column) and startingPos[col] (prefix sums storing the starting slot of each transposed row). Because each entry is placed directly into its final slot in a single pass, fast transpose eliminates repeated scanning on large sparse matrices.
For a three-dimensional array A[P][M][N] (with planes, rows, and columns, 0-based), Row-Major order maps A[p][i][j] to , whereas Column-Major order maps A[p][i][j] to . For example, in A[3][4][5] with and , Row-Major address of A[1][2][3] is .
5.4 Worked Asymptotic Complexity Analysis of Loop Patterns
Determining time complexity from C source code relies on counting dominant loop iterations as a function of :
- Single Linear Loop:
for (i = 0; i < n; i++)executes iterations → . - Dependent Nested Loops:
for (i = 0; i < n; i++) for (j = i + 1; j < n; j++)executes iterations → (characteristic of Bubble, Selection, and Insertion Sort). - Multiplicative / Halving Loop:
while (n > 1) { n = n / 2; }halves the problem each step, executing iterations → (characteristic of Binary Search). - Linearithmic Nested Loop: An outer loop enclosing an inner halving loop executes operations → .
| Input Size | |||||
|---|---|---|---|---|---|
| 16 | 1 | 4 | 16 | 64 | 256 |
| 1,024 | 1 | 10 | 1,024 | 10,240 | 1,048,576 |
| 1,048,576 | 1 | 20 | 1,048,576 | 20,971,520 |
Module II: Linked Lists
Chapter 1: Concept of Linked Lists and Comparison with Arrays
1.1 Dynamic Nodes and Heap Memory Representation
A linked list is a linear, dynamic data structure formed by chaining independent memory blocks called nodes. Unlike arrays, which require a single contiguous block of memory, linked list nodes can be scattered arbitrarily across the system heap. Each node encapsulates two components: a data field (one or more payload attributes) and one or more link (pointer) fields storing the physical memory address of adjacent nodes.
An external pointer variable—commonly named head or start—holds the memory address of the first node. An empty list is represented by head == NULL. In C, nodes are allocated dynamically at runtime via malloc(sizeof(Node)) when elements are inserted and returned to the heap via free(ptr) when elements are deleted. Consequently, linked lists never suffer from static capacity overflow as long as heap memory remains available.
Disciplined pointer hygiene is essential when managing dynamic memory: always check whether malloc returns NULL (indicating heap exhaustion), always call free() on removed nodes to avoid memory leaks, and immediately reset freed pointers to NULL if they remain in scope to prevent dangling pointer dereferences.
1.2 Linked List versus Array
Understanding when to select an array versus a linked list is a core engineering decision governed by access patterns, mutation frequency, and memory constraints.
| Comparison Criterion | Array | Linked List |
|---|---|---|
| Memory Layout | Contiguous block of adjacent bytes | Non-contiguous heap nodes connected by pointers |
| Size Flexibility | Fixed at creation (resizing requires reallocation) | Dynamic; grows and shrinks node by node |
| Random Access | via base + offset arithmetic | sequential traversal from head |
| Insertion / Deletion at Front | due to shifting all subsequent items | by updating two pointers |
| Insertion / Deletion at Middle (given ptr) | shifting cost | pointer relinking once node is located ( to locate) |
| Memory Overhead | Zero pointer overhead; potential unused capacity | Extra pointer(s) per node; zero unused slots |
| CPU Cache Performance | Excellent spatial locality (contiguous) | Poor spatial locality (pointer chasing) |
| Binary Search Support | Yes, in time | Not efficient ( to reach midpoint) |
Chapter 2: Singly Linked List
2.1 Memory Representation of Singly Linked List
In a singly linked list (SLL), each node contains a data field and a single pointer field next referencing the successor node. The final node's next pointer is set to NULL, acting as a sentinel marking the end of the chain. Because each node holds only a forward link, traversal is strictly unidirectional from head toward NULL.
#include <stdio.h>
#include <stdlib.h>
typedef struct SNode {
int data;
struct SNode *next;
} SNode;
SNode* createSNode(int val) {
SNode *node = (SNode*)malloc(sizeof(SNode));
if (node == NULL) return NULL;
node->data = val;
node->next = NULL;
return node;
}2.2 Traversing and Searching in Singly Linked List
Traversing visits every node sequentially: initialize curr = head, process curr->data, and advance curr = curr->next while curr != NULL. This takes time and extra space. Searching executes the same loop, testing curr->data == key at each node and returning the matching node pointer (or 1-based position) immediately upon match, or NULL if the end is reached. Best case is (key at head); worst and average cases are .
2.3 Insertion Operations in Singly Linked List
Inserting a new node into an SLL involves three distinct cases depending on the target location:
- Insertion at the Beginning (): Allocate
newNode, assignnewNode->next = head, and updatehead = newNode. This single sequence works seamlessly whether the list is initially empty or non-empty. - Insertion at the End ( without tail pointer): Allocate
newNodewithnewNode->next = NULL. Ifhead == NULL, sethead = newNode. Otherwise, traverse withcurr = headuntilcurr->next == NULL, then setcurr->next = newNode. - Insertion at a Specified Position (): For 1-based position
pos, ifpos == 1, perform front insertion. Otherwise, advancecurrforpos - 2steps to reach the predecessor node (checking forcurr == NULLto guard against out-of-range positions), then executenewNode->next = curr->nextfollowed bycurr->next = newNode.
A critical pointer-ordering invariant applies when inserting after a node curr: always assign newNode->next = curr->next before overwriting curr->next = newNode; reversing these two lines loses the reference to the remainder of the list.
2.4 Deletion Operations in Singly Linked List
Deleting a node from an SLL must handle empty-list underflow, single-node lists, and memory deallocation:
- Deletion from the Beginning (): If
head == NULL, report underflow. Otherwise, storetemp = head, advancehead = head->next, and callfree(temp). - Deletion from the End (): If
head == NULL, return. Ifhead->next == NULL(single node), freeheadand sethead = NULL. Otherwise, traverse untilcurr->next->next == NULL(stopping at the second-last node), callfree(curr->next), and setcurr->next = NULL. - Deletion by Key or Position (): Maintain two pointers,
prev(initiallyNULL) andcurr(initiallyhead). Advance both untilcurr->data == keyorcurr == NULL. If found at the head (prev == NULL), sethead = curr->next; otherwise, setprev->next = curr->next. Finally callfree(curr).
void traverseSLL(SNode *head) {
for (SNode *curr = head; curr != NULL; curr = curr->next) {
printf("%d -> ", curr->data);
}
printf("NULL\n");
}
SNode* searchSLL(SNode *head, int key) {
for (SNode *curr = head; curr != NULL; curr = curr->next) {
if (curr->data == key) return curr;
}
return NULL;
}
void insertFrontSLL(SNode **head, int val) {
SNode *n = createSNode(val);
if (!n) return;
n->next = *head;
*head = n;
}
void insertEndSLL(SNode **head, int val) {
SNode *n = createSNode(val);
if (!n) return;
if (*head == NULL) { *head = n; return; }
SNode *curr = *head;
while (curr->next != NULL) curr = curr->next;
curr->next = n;
}
int insertAtPosSLL(SNode **head, int pos, int val) {
if (pos < 1) return 0;
if (pos == 1) { insertFrontSLL(head, val); return 1; }
SNode *curr = *head;
for (int i = 1; i < pos - 1 && curr != NULL; i++) curr = curr->next;
if (curr == NULL) return 0;
SNode *n = createSNode(val);
if (!n) return 0;
n->next = curr->next;
curr->next = n;
return 1;
}
int deleteFrontSLL(SNode **head) {
if (*head == NULL) return 0;
SNode *tmp = *head;
*head = (*head)->next;
free(tmp);
return 1;
}
int deleteEndSLL(SNode **head) {
if (*head == NULL) return 0;
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
return 1;
}
SNode *curr = *head;
while (curr->next->next != NULL) curr = curr->next;
free(curr->next);
curr->next = NULL;
return 1;
}
int deleteByKeySLL(SNode **head, int key) {
SNode *curr = *head, *prev = NULL;
while (curr != NULL && curr->data != key) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return 0;
if (prev == NULL) *head = curr->next;
else prev->next = curr->next;
free(curr);
return 1;
}2.5 Essential Singly Linked List Algorithms: Reversal and Polynomial Addition
Two classic algorithms demonstrate pointer manipulation on singly linked lists. In-place list reversal uses three pointers—prev (initially NULL), curr (initially head), and nextNode—to reverse every next link in a single pass using extra space. Polynomial representation stores each non-zero term of a polynomial as a node containing (coeff, exp, next) in descending order of exponent, allowing two polynomials to be added in time using a merge-like scan.
void reverseSLL(SNode **head) {
SNode *prev = NULL, *curr = *head, *nextNode = NULL;
while (curr != NULL) {
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
*head = prev;
}
SNode* findMiddleSLL(SNode *head) {
SNode *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}Chapter 3: Doubly Linked List
3.1 Memory Representation and Bidirectional Linking
A doubly linked list (DLL) augments each node with two pointers: prev (pointing to the immediate predecessor) and next (pointing to the immediate successor). The prev field of the first node and the next field of the last node are both NULL. While each node requires one additional pointer of storage compared to an SLL, bidirectional linking provides two major algorithmic advantages: (1) traversal can proceed in both forward and backward directions, and (2) deleting a node given only its pointer del executes in time without scanning from head to find its predecessor.
3.2 Traversing, Searching, Insertion, and Deletion in DLL
Forward Traversal starts at head and follows next pointers until NULL. Backward Traversal moves to the last node (or starts at a maintained tail pointer) and follows prev pointers back to NULL. Searching inspects nodes sequentially in time.
Insertion Operations:
- Insert at Beginning (): Allocate
newNode, setnewNode->prev = NULLandnewNode->next = head. Ifhead != NULL, updatehead->prev = newNode. Finally sethead = newNode. - Insert at End ( without tail): If
head == NULL, perform front insertion. Otherwise traverse to the last nodecurr, setcurr->next = newNode,newNode->prev = curr, andnewNode->next = NULL. - Insert After a Given Node
curr(): SetnewNode->next = curr->nextandnewNode->prev = curr. Ifcurr->next != NULL, setcurr->next->prev = newNode. Finally setcurr->next = newNode.
Deletion Operations: To delete a target node del (located by front, end, or key search): if del == head, update head = del->next. If del->next != NULL, link del->next->prev = del->prev. If del->prev != NULL, link del->prev->next = del->next. Release memory with free(del).
| DLL Operation | Pointers Updated | Edge Cases Handled | Time Complexity |
|---|---|---|---|
| Insert Front | n->next, head->prev, head | Empty list (head == NULL) | |
| Insert End | tail->next, n->prev | Empty list | / with tail |
| Insert After Node | n->next, n->prev, curr->next->prev, curr->next | curr is last node | |
Delete Node del | del->prev->next, del->next->prev, head | Head node, tail node, single node |
typedef struct DNode {
int data;
struct DNode *prev;
struct DNode *next;
} DNode;
DNode* createDNode(int val) {
DNode *n = (DNode*)malloc(sizeof(DNode));
if (!n) return NULL;
n->data = val;
n->prev = n->next = NULL;
return n;
}
void traverseForwardDLL(DNode *head) {
for (DNode *curr = head; curr != NULL; curr = curr->next) {
printf("%d <-> ", curr->data);
}
printf("NULL\n");
}
void traverseBackwardDLL(DNode *head) {
if (head == NULL) return;
DNode *curr = head;
while (curr->next != NULL) curr = curr->next;
while (curr != NULL) {
printf("%d <-> ", curr->data);
curr = curr->prev;
}
printf("NULL\n");
}
DNode* searchDLL(DNode *head, int key) {
for (DNode *curr = head; curr != NULL; curr = curr->next) {
if (curr->data == key) return curr;
}
return NULL;
}
void insertFrontDLL(DNode **head, int val) {
DNode *n = createDNode(val);
if (!n) return;
n->next = *head;
if (*head != NULL) (*head)->prev = n;
*head = n;
}
void insertEndDLL(DNode **head, int val) {
if (*head == NULL) { insertFrontDLL(head, val); return; }
DNode *n = createDNode(val);
if (!n) return;
DNode *curr = *head;
while (curr->next != NULL) curr = curr->next;
curr->next = n;
n->prev = curr;
}
void insertAfterDLL(DNode *curr, int val) {
if (curr == NULL) return;
DNode *n = createDNode(val);
if (!n) return;
n->next = curr->next;
n->prev = curr;
if (curr->next != NULL) curr->next->prev = n;
curr->next = n;
}
void deleteNodeDLL(DNode **head, DNode *del) {
if (*head == NULL || del == NULL) return;
if (*head == del) *head = del->next;
if (del->next != NULL) del->next->prev = del->prev;
if (del->prev != NULL) del->prev->next = del->next;
free(del);
}
int deleteByKeyDLL(DNode **head, int key) {
DNode *target = searchDLL(*head, key);
if (target == NULL) return 0;
deleteNodeDLL(head, target);
return 1;
}Chapter 4: Circular Linked List Concepts
4.1 Structural Concept, Invariants, and Applications
A circular linked list (CLL) modifies the standard linked list by connecting the last node's next pointer back to the first node (head) instead of storing NULL. In a doubly circular linked list, the first node's prev pointer also points to the last node. Consequently, there is no NULL terminator inside a non-empty circular list, and a single-node circular list satisfies head->next == head.
Traversal Termination: Because following next pointers loops indefinitely, traversal must record the starting address (typically head) and use a do-while loop that stops when curr == head again. Tail-Pointer Optimization: Rather than storing head, circular lists frequently maintain a single pointer last to the final node. From last, both the end of the list (last) and the start of the list (last->next) are reachable in time.
Applications: Circular linked lists are ideal for round-robin operating system time-slicing (where the scheduler cycles through ready processes continuously), multiplayer turn rotation in games, and continuous media playlists. (Full insertion and deletion algorithms for circular linked lists are covered in Module V.)
| Feature | Singly Linked List | Doubly Linked List | Circular Linked List |
|---|---|---|---|
| Pointers per Node | 1 (next) | 2 (prev, next) | 1 (next) or 2 (doubly circular) |
| Last Node Link | NULL | NULL | Points to head |
| Traversal | Forward only | Forward and Backward | Cyclic wrap-around |
| Loop Termination | curr == NULL | curr == NULL | curr == head (after 1st step) |
| Delete Arbitrary Node (given ptr) | to find predecessor | via prev | singly / doubly |
4.2 Round-Robin Scheduling Simulation and Memory Hygiene
To illustrate why circular linked lists excel in cyclic resource allocation, consider three ready processes P1, P2, and P3 linked in a ring where last points to P3 and last->next points to P1. On each CPU time-quantum tick, the scheduler executes the process at curr = last->next, then advances last = last->next in time without resetting to head or checking for NULL. When P2 completes execution, it is unlinked in a single pointer update, leaving P1 → P3 → P1 intact.
Chapter 5: Advanced Linked List Patterns and Applications
5.1 Sorted Insertion and Merging Two Sorted Singly Linked Lists
Maintaining a singly linked list in sorted ascending order requires scanning until finding the first node whose data exceeds the new key, then inserting immediately before it. Merging two sorted singly linked lists L1 and L2 into a single sorted list runs in time and auxiliary space by relinking existing nodes using a dummy sentinel node, avoiding any new heap allocations.
SNode* mergeSortedSLL(SNode *l1, SNode *l2) {
SNode dummy;
SNode *tail = &dummy;
dummy.next = NULL;
while (l1 != NULL && l2 != NULL) {
if (l1->data <= l2->data) {
tail->next = l1; l1 = l1->next;
} else {
tail->next = l2; l2 = l2->next;
}
tail = tail->next;
}
tail->next = (l1 != NULL) ? l1 : l2;
return dummy.next;
}
void removeDuplicatesSortedSLL(SNode *head) {
SNode *curr = head;
while (curr != NULL && curr->next != NULL) {
if (curr->data == curr->next->data) {
SNode *dup = curr->next;
curr->next = dup->next;
free(dup);
} else {
curr = curr->next;
}
}
}
int countNodesSLL(const SNode *head) {
int count = 0;
for (const SNode *p = head; p != NULL; p = p->next) count++;
return count;
}5.2 Reversing a Doubly Linked List and Deallocating Entire Lists
Reversing a doubly linked list swaps the prev and next pointers of every node in a single pass and updates head to the last visited node. When a program finishes using any linked list, every node must be freed sequentially from head to NULL—storing nextNode = curr->next before calling free(curr)—to prevent memory leaks and dangling pointer reads.
void reverseDLL(DNode **head) {
DNode *curr = *head, *temp = NULL;
while (curr != NULL) {
temp = curr->prev;
curr->prev = curr->next;
curr->next = temp;
curr = curr->prev; /* moves to original next node */
}
if (temp != NULL) *head = temp->prev;
}
void freeAllSLL(SNode **head) {
SNode *curr = *head;
while (curr != NULL) {
SNode *nextNode = curr->next;
free(curr);
curr = nextNode;
}
*head = NULL;
}5.3 Polynomial Addition Using Singly Linked Lists
Representing sparse polynomials such as in an array would waste 98 zero coefficients. Using a singly linked list where each node stores (coeff, exp, next) in descending exponent order stores only the 3 non-zero terms. Adding two polynomials advances pointers p and q simultaneously: if p->exp > q->exp, copy p's term; if q->exp > p->exp, copy q's term; if exponents match and p->coeff + q->coeff != 0, emit a node with the summed coefficient and advance both pointers.
typedef struct PolyNode {
int coeff, exp;
struct PolyNode *next;
} PolyNode;
PolyNode* addPoly(PolyNode *p, PolyNode *q) {
PolyNode dummy;
PolyNode *tail = &dummy;
dummy.next = NULL;
while (p != NULL && q != NULL) {
PolyNode *n = (PolyNode*)malloc(sizeof(PolyNode));
n->next = NULL;
if (p->exp > q->exp) {
n->coeff = p->coeff; n->exp = p->exp; p = p->next;
} else if (q->exp > p->exp) {
n->coeff = q->coeff; n->exp = q->exp; q = q->next;
} else {
int sum = p->coeff + q->coeff;
p = p->next; q = q->next;
if (sum == 0) { free(n); continue; }
n->coeff = sum; n->exp = (p ? p->exp : 0);
}
tail->next = n;
tail = n;
}
while (p != NULL) {
PolyNode *n = (PolyNode*)malloc(sizeof(PolyNode));
n->coeff = p->coeff; n->exp = p->exp; n->next = NULL;
tail->next = n; tail = n; p = p->next;
}
while (q != NULL) {
PolyNode *n = (PolyNode*)malloc(sizeof(PolyNode));
n->coeff = q->coeff; n->exp = q->exp; n->next = NULL;
tail->next = n; tail = n; q = q->next;
}
return dummy.next;
}5.4 Cycle Detection in Linked Lists (Floyd's Tortoise and Hare)
To verify whether a singly linked list terminates cleanly at NULL or contains an accidental cycle, Floyd's cycle-finding algorithm advances a slow pointer by one node per step and a fast pointer by two nodes per step. If fast reaches NULL, the list is linear and acyclic; if slow == fast at any point inside the loop, a cycle exists. This runs in time and space.
Module III: Stack & Queue
Chapter 1: Stack Abstract Data Type and Implementations
1.1 Concept, LIFO Principle, and Core Operations
A stack is a linear abstract data type governed by the Last-In, First-Out (LIFO) access policy: the most recently inserted element is always the first element removed. All insertions and deletions are restricted to a single end called the top. Attempting to push onto a full fixed-size stack causes Stack Overflow, while attempting to pop or peek an empty stack causes Stack Underflow.
push(x): Places element at the top of the stack in time.pop(): Removes and returns the current top element in time.peek()/top(): Inspects the top element without removing it in time.isEmpty()andisFull(): Return boolean status indicating whether the stack is empty or at capacity.
1.2 Array Implementation versus Linked List Implementation
In an array-based stack, a fixed array items[MAX] and an integer index top (initialized to -1) track the state. push increments top and stores the value; pop reads items[top] and decrements top. Array stacks offer zero pointer overhead and high cache locality, but are constrained by compile-time capacity MAX (unless dynamically resized via realloc doubling).
In a linked-list-based stack, the top pointer serves as the head of a singly linked list. push allocates a new node and prepends it at top; pop removes and frees the node at top. Both operations run in time with dynamic capacity bounded only by available heap memory.
| Metric | Array-Based Stack | Linked-List-Based Stack |
|---|---|---|
| Capacity | Fixed (MAX) unless resized | Dynamic (grows until heap full) |
push / pop Complexity | ||
| Memory per Element | Payload only (zero pointer overhead) | Payload + 1 pointer (next) |
| Overflow Condition | top == MAX - 1 | malloc returns NULL |
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct {
int items[MAX];
int top;
} ArrayStack;
void initArrayStack(ArrayStack *s) { s->top = -1; }
int isEmptyArr(const ArrayStack *s) { return s->top == -1; }
int isFullArr(const ArrayStack *s) { return s->top == MAX - 1; }
int pushArr(ArrayStack *s, int val) {
if (isFullArr(s)) return 0;
s->items[++(s->top)] = val;
return 1;
}
int popArr(ArrayStack *s, int *out) {
if (isEmptyArr(s)) return 0;
*out = s->items[(s->top)--];
return 1;
}
int peekArr(const ArrayStack *s, int *out) {
if (isEmptyArr(s)) return 0;
*out = s->items[s->top];
return 1;
}
typedef struct StackNode {
int data;
struct StackNode *next;
} StackNode;
int pushLinked(StackNode **top, int val) {
StackNode *n = (StackNode*)malloc(sizeof(StackNode));
if (n == NULL) return 0;
n->data = val;
n->next = *top;
*top = n;
return 1;
}
int popLinked(StackNode **top, int *out) {
if (*top == NULL) return 0;
StackNode *tmp = *top;
*out = tmp->data;
*top = tmp->next;
free(tmp);
return 1;
}Chapter 2: Applications of Stack and Expression Processing
2.1 Polish and Reverse Polish Notations
Arithmetic expressions can be represented in three notations based on where operators appear relative to their operands:
- Infix Notation: The operator sits between its operands, e.g., . Although natural for human reading, infix expressions require explicit operator precedence rules, associativity rules, and parentheses to resolve ambiguity.
- Polish (Prefix) Notation: Proposed by logician Jan Lukasiewicz, the operator precedes its operands, e.g., . Parentheses are completely unnecessary.
- Reverse Polish (Postfix) Notation: The operator follows its operands, e.g., . Parentheses are unnecessary, and compilers favor postfix notation because it can be evaluated in a single left-to-right pass using a stack.
| Infix Expression | Prefix (Polish) | Postfix (Reverse Polish) |
|---|---|---|
| A ^ B ^ C (right-assoc.) | ^ A ^ B C | A B C ^ ^ |
2.2 Infix to Postfix Conversion Using Stack
To convert a parenthesized infix expression into postfix in time, scan tokens from left to right using an operator stack with precedence levels: ^ (3, right-associative), * / % (2, left-associative), and + - (1, left-associative):
- If the token is an operand (letter or digit), append it immediately to the postfix output.
- If the token is
(, push it onto the operator stack. - If the token is
), pop operators from the stack and append them to the output until(is reached; pop and discard(. - If the token is an operator
op, repeatedly pop operators from the stack to the output while the stack top is not(and either (a) stack top has strictly higher precedence thanop, or (b) stack top has equal precedence andopis left-associative. Then pushop. - After scanning the entire input, pop all remaining operators onto the output.
| Step | Token | Action | Operator Stack | Postfix Output |
|---|---|---|---|---|
| 1 | A | Append operand | (empty) | A |
| 2 | + | Push + | + | A |
| 3 | ( | Push ( | + ( | A |
| 4 | B | Append operand | + ( | A B |
| 5 | * | Push * | + ( * | A B |
| 6 | C | Append operand | + ( * | A B C |
| 7 | - | Pop * (higher prec.), push - | + ( - | A B C * |
| 8 | D | Append operand | + ( - | A B C * D |
| 9 | ) | Pop -, discard ( | + | A B C * D - |
| 10 | End | Pop remaining + | (empty) | A B C * D - + |
2.3 Evaluation of Postfix Expression Using Stack
Postfix evaluation scans the expression left to right using an integer operand stack. Each numeric operand is pushed onto the stack. When a binary operator op appears, two operands are popped: the first popped value is the right operand op2, and the second popped value is the left operand op1 (order matters for non-commutative - and /). The result of op1 op op2 is pushed back onto the stack. At the end of the scan, the sole remaining stack element is the final value.
| Token | Operation | Operand Stack (Bottom → Top) |
|---|---|---|
6 | Push 6 | [6] |
2 | Push 2 | [6, 2] |
3 | Push 3 | [6, 2, 3] |
+ | Pop op2=3, op1=2 → 2+3=5, push 5 | [6, 5] |
* | Pop op2=5, op1=6 → 6*5=30, push 30 | [30] |
4 | Push 4 | [30, 4] |
- | Pop op2=4, op1=30 → 30-4=26, push 26 | [26] |
#include <ctype.h>
int precedence(char op) {
if (op == '^') return 3;
if (op == '*' || op == '/' || op == '%') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
void infixToPostfix(const char *infix, char *postfix) {
char st[MAX];
int top = -1, k = 0;
for (int i = 0; infix[i] != '\0'; i++) {
char ch = infix[i];
if (isalnum((unsigned char)ch)) {
postfix[k++] = ch;
} else if (ch == '(') {
st[++top] = ch;
} else if (ch == ')') {
while (top >= 0 && st[top] != '(') postfix[k++] = st[top--];
if (top >= 0) top--;
} else {
while (top >= 0 && st[top] != '(' &&
(precedence(st[top]) > precedence(ch) ||
(precedence(st[top]) == precedence(ch) && ch != '^'))) {
postfix[k++] = st[top--];
}
st[++top] = ch;
}
}
while (top >= 0) postfix[k++] = st[top--];
postfix[k] = '\0';
}
int evalPostfix(const char *expr) {
ArrayStack s;
initArrayStack(&s);
for (int i = 0; expr[i] != '\0'; i++) {
char ch = expr[i];
if (isdigit((unsigned char)ch)) {
pushArr(&s, ch - '0');
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
int op2 = 0, op1 = 0;
popArr(&s, &op2);
popArr(&s, &op1);
if (ch == '+') pushArr(&s, op1 + op2);
else if (ch == '-') pushArr(&s, op1 - op2);
else if (ch == '*') pushArr(&s, op1 * op2);
else if (ch == '/' && op2 != 0) pushArr(&s, op1 / op2);
}
}
int res = 0;
popArr(&s, &res);
return res;
}
int isBalanced(const char *expr) {
char st[MAX];
int top = -1;
for (int i = 0; expr[i] != '\0'; i++) {
char c = expr[i];
if (c == '(' || c == '[' || c == '{') st[++top] = c;
else if (c == ')' || c == ']' || c == '}') {
if (top < 0) return 0;
char open = st[top--];
if ((c == ')' && open != '(') || (c == ']' && open != '[') ||
(c == '}' && open != '{')) return 0;
}
}
return top == -1;
}2.4 Recursion and the System Call Stack
When a program invokes a function—including a recursive function calling itself—the runtime environment allocates an activation record (stack frame) containing local variables, parameters, and the return address, pushing it onto the system call stack. When the base case is reached, frames unwind in strict LIFO order, returning intermediate values to each caller. Thus, every recursive algorithm implicitly uses a stack of depth proportional to the recursion height (e.g., for factorial, for Tower of Hanoi).
Chapter 3: Queue, Deque, and Priority Queue
3.1 Queue Concept, Array and Linked List Implementations
A queue is a linear data structure adhering to the First-In, First-Out (FIFO) discipline: insertions occur exclusively at the rear (enqueue) and deletions occur exclusively at the front (dequeue). In a naive linear array queue, repeated insertions and deletions advance front and rear toward MAX - 1, leaving empty slots at low indices unreachable. A circular queue eliminates this false-full condition by wrapping indices modulo MAX: rear = (rear + 1) % MAX and front = (front + 1) % MAX.
In a linked-list queue, maintaining both front and rear pointers allows both enqueue (attaching a new node after rear) and dequeue (removing the node at front) to execute in time without fixed capacity limits. Applications of queues include CPU round-robin scheduling, printer job spooling, asynchronous I/O buffering, and Breadth-First Search (BFS) traversal in graphs.
typedef struct {
int items[MAX];
int front, rear, count;
} CircularQueue;
void initCQ(CircularQueue *q) { q->front = 0; q->rear = -1; q->count = 0; }
int enqueueCQ(CircularQueue *q, int val) {
if (q->count == MAX) return 0;
q->rear = (q->rear + 1) % MAX;
q->items[q->rear] = val;
q->count++;
return 1;
}
int dequeueCQ(CircularQueue *q, int *out) {
if (q->count == 0) return 0;
*out = q->items[q->front];
q->front = (q->front + 1) % MAX;
q->count--;
return 1;
}
typedef struct QNode {
int data;
struct QNode *next;
} QNode;
typedef struct {
QNode *front, *rear;
} LinkedQueue;
void initLQ(LinkedQueue *q) { q->front = q->rear = NULL; }
void enqueueLQ(LinkedQueue *q, int val) {
QNode *n = (QNode*)malloc(sizeof(QNode));
if (!n) return;
n->data = val; n->next = NULL;
if (q->rear == NULL) { q->front = q->rear = n; return; }
q->rear->next = n;
q->rear = n;
}
int dequeueLQ(LinkedQueue *q, int *out) {
if (q->front == NULL) return 0;
QNode *tmp = q->front;
*out = tmp->data;
q->front = q->front->next;
if (q->front == NULL) q->rear = NULL;
free(tmp);
return 1;
}3.2 Deque (Double-Ended Queue) and Types
A Deque (Double-Ended Queue) generalizes both stacks and queues by allowing insertions and deletions at both the front and rear ends. Deques support four operations: insertFront, insertRear, deleteFront, and deleteRear, all in time using a circular array or doubly linked list. Two constrained variants exist:
- Input-Restricted Deque: Insertions are permitted at only one end (rear), while deletions are permitted at both front and rear.
- Output-Restricted Deque: Deletions are permitted at only one end (front), while insertions are permitted at both front and rear.
typedef struct {
int items[MAX];
int front, rear, count;
} Deque;
void initDeque(Deque *d) { d->front = 0; d->rear = -1; d->count = 0; }
int insertFrontDeque(Deque *d, int val) {
if (d->count == MAX) return 0;
d->front = (d->front - 1 + MAX) % MAX;
d->items[d->front] = val;
if (d->count == 0) d->rear = d->front;
d->count++;
return 1;
}
int deleteRearDeque(Deque *d, int *out) {
if (d->count == 0) return 0;
*out = d->items[d->rear];
d->rear = (d->rear - 1 + MAX) % MAX;
d->count--;
return 1;
}3.3 Priority Queues (Basic Concepts)
A priority queue assigns each element a priority key. Unlike a strict FIFO queue, elements are dequeued in order of priority rather than arrival time. In an ascending (min) priority queue, the element with the smallest key is removed first; in a descending (max) priority queue, the element with the largest key is removed first. Elements with equal priority are served in FIFO order. Priority queues can be implemented using unsorted arrays ( insert, extract), sorted lists ( insert, extract), or binary heaps ( for both), and are vital in operating system task scheduling, interrupt handling, and shortest-path routing.
| Queue Variant | Insertion End(s) | Deletion Rule | Primary Application |
|---|---|---|---|
| Linear / Circular Queue | Rear only | Front only (FIFO) | CPU scheduling, BFS, spooling |
| Input-Restricted Deque | Rear only | Front or Rear | Undo/redo with bounded history |
| Output-Restricted Deque | Front or Rear | Front only | Work-stealing task schedulers |
| Priority Queue | Anywhere (by key) | Highest/Lowest priority | Dijkstra, OS interrupt handling |
Chapter 4: Advanced Stack & Queue Implementations and Traces
4.1 Two Stacks in a Single Array
To maximize memory utilization when two independent stacks share a fixed buffer arr[MAX], Stack 1 grows upward from index 0 (top1 = -1 initially) while Stack 2 grows downward from index MAX - 1 (top2 = MAX initially). Overflow occurs only when the two tops meet (top1 + 1 == top2), allowing either stack to occupy nearly the entire buffer whenever the other stack is small.
typedef struct {
int arr[MAX];
int top1, top2;
} TwoStacks;
void initTwoStacks(TwoStacks *ts) { ts->top1 = -1; ts->top2 = MAX; }
int pushStack1(TwoStacks *ts, int val) {
if (ts->top1 + 1 == ts->top2) return 0;
ts->arr[++(ts->top1)] = val;
return 1;
}
int pushStack2(TwoStacks *ts, int val) {
if (ts->top1 + 1 == ts->top2) return 0;
ts->arr[--(ts->top2)] = val;
return 1;
}4.2 Infix to Prefix (Polish) Conversion Algorithm
Converting an infix expression to Prefix (Polish) notation reuses the infix-to-postfix algorithm via a three-step transformation: (1) reverse the infix string while swapping ( and ); (2) convert the reversed string to postfix (treating equal-precedence operators carefully so associativity is preserved); and (3) reverse the resulting postfix string to obtain the final prefix expression. For example, converting (A + B) * C reverses to C * (B + A), yields postfix C B A + *, and reverses to prefix * + A B C.
4.3 Sorted Linked-List Priority Queue
In a linked-list ascending priority queue, elements are maintained in sorted ascending order of priority key. enqueuePQ traverses the list to insert the new node at its sorted position in time, while dequeuePQ removes and returns the front node (minimum priority value) in time.
typedef struct PQNode {
int data;
int priority; /* smaller value = higher priority */
struct PQNode *next;
} PQNode;
void enqueuePQ(PQNode **front, int data, int prio) {
PQNode *n = (PQNode*)malloc(sizeof(PQNode));
if (!n) return;
n->data = data; n->priority = prio; n->next = NULL;
if (*front == NULL || prio < (*front)->priority) {
n->next = *front;
*front = n;
return;
}
PQNode *curr = *front;
while (curr->next != NULL && curr->next->priority <= prio) {
curr = curr->next;
}
n->next = curr->next;
curr->next = n;
}
int dequeuePQ(PQNode **front, int *outData) {
if (*front == NULL) return 0;
PQNode *tmp = *front;
*outData = tmp->data;
*front = (*front)->next;
free(tmp);
return 1;
}4.4 Stack-Frame Trace for Recursive Factorial
Tracing fact(4) illustrates LIFO call-stack behavior: fact(4) pushes frame n=4 and waits for fact(3); fact(3) pushes n=3; fact(2) pushes n=2; fact(1) hits the base case and returns 1. Unwinding pops n=2 returning 2 * 1 = 2, pops n=3 returning 3 * 2 = 6, and pops n=4 returning 4 * 6 = 24.
4.5 Implementing a Queue Using Two Stacks
A FIFO queue can be simulated using two LIFO stacks, inStack and outStack. enqueue(x) simply pushes onto inStack in time. dequeue() pops from outStack; if outStack is empty, all elements from inStack are popped and pushed onto outStack, reversing their order so the oldest element sits on top. Because each element moves from inStack to outStack at most once, the amortized time complexity per operation is .
typedef struct {
ArrayStack inStack;
ArrayStack outStack;
} QueueUsingStacks;
void initQUS(QueueUsingStacks *q) {
initArrayStack(&q->inStack);
initArrayStack(&q->outStack);
}
int enqueueQUS(QueueUsingStacks *q, int val) {
return pushArr(&q->inStack, val);
}
int dequeueQUS(QueueUsingStacks *q, int *out) {
if (isEmptyArr(&q->outStack)) {
int val = 0;
while (popArr(&q->inStack, &val)) {
pushArr(&q->outStack, val);
}
}
return popArr(&q->outStack, out);
}4.6 Tower of Hanoi and Recursion Depth
The classic Tower of Hanoi problem moves disks from source peg A to destination peg C using auxiliary peg B under the rule that a larger disk may never sit atop a smaller disk. The recursive recurrence with yields total disk moves while consuming system call-stack frames.
4.7 Resizable Dynamic Array Stack and Amortized Complexity
To overcome fixed-capacity overflow in array stacks without switching to linked lists, a dynamic array stack allocates an initial heap buffer of capacity and doubles the buffer size () via realloc() whenever top == C - 1. Although a single resizing push takes time to copy existing elements, doubling ensures that consecutive pushes perform at most total copies, yielding amortized time per push.
void towerOfHanoi(int n, char src, char aux, char dest) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", src, dest);
return;
}
towerOfHanoi(n - 1, src, dest, aux);
printf("Move disk %d from %c to %c\n", n, src, dest);
towerOfHanoi(n - 1, aux, src, dest);
}
typedef struct {
int *items;
int top, capacity;
} DynStack;
void pushDyn(DynStack *s, int val) {
if (s->top == s->capacity - 1) {
s->capacity *= 2;
s->items = (int*)realloc(s->items, sizeof(int) * s->capacity);
}
s->items[++(s->top)] = val;
}Module IV: Trees & Binary Search Trees
Chapter 1: Tree Terminologies and Binary Tree Taxonomy
1.1 Concept of Trees and Standard Terminologies
A tree is a non-linear, acyclic, hierarchical data structure consisting of a finite set of nodes connected by directed edges. One node is designated as the root (having no parent), and every remaining node has exactly one parent node. A tree with nodes always contains exactly edges.
- Root: The topmost node of the hierarchy with zero incoming edges.
- Parent, Child, and Siblings: If an edge connects node to node , is the parent of , and is a child of . Nodes sharing the same parent are siblings.
- Leaf (External Node) vs. Internal Node: A node with zero children is a leaf; any node with at least one child is an internal node.
- Degree: The degree of a node is its number of children; the degree of a tree is the maximum degree among all its nodes.
- Level and Depth: The root sits at level 0 (depth 0). If a node is at level , its children sit at level .
- Height: The height of a node is the number of edges on the longest downward path from that node to a leaf. A leaf has height 0; an empty tree has height -1.
- Path, Subtree, and Forest: A path is a sequence of consecutive edges from an ancestor to a descendant. Every node together with all its descendants forms a subtree. A disjoint set of trees is called a forest.
1.2 Binary Tree Properties and Types
A binary tree is a specialized tree in which every node has at most two children, explicitly distinguished as the left child and the right child. Key mathematical properties of binary trees govern their capacity and balance:
- At level (with root at level 0), a binary tree contains at most nodes.
- A binary tree of height contains at most nodes and at least nodes (when skewed).
- For a binary tree with nodes, the minimum possible height is and the maximum height is .
- In any non-empty binary tree, the number of leaf nodes equals the number of nodes of degree 2 () plus one: .
Binary trees are categorized into three primary structural types:
- Full (Strict / Proper) Binary Tree: Every node has either 0 children (leaf) or 2 children (internal); no node has exactly 1 child.
- Complete Binary Tree: Every level except possibly the last is completely filled, and all nodes in the last level are positioned as far left as possible. This compact layout enables efficient array representation (used in binary heaps).
- Perfect Binary Tree: Every internal node has exactly 2 children and all leaves lie at the exact same depth . It contains exactly nodes and leaves.
| Binary Tree Type | Structural Invariant | Node Count at Height | Primary Use Case |
|---|---|---|---|
| Full Binary Tree | Every node has 0 or 2 children | Expression trees, Huffman trees | |
| Complete Binary Tree | Levels 0..h-1 full; level h packed left | Binary heaps, priority queues | |
| Perfect Binary Tree | All internal nodes have 2 children; leaves at depth | Exactly | Theoretical bounds, balanced indexing |
1.3 Expression Trees
An expression tree is a binary tree representing an arithmetic or Boolean expression. Leaf nodes store operands (variables or constants), while internal nodes store operators. To construct an expression tree from a postfix expression, scan left to right with a stack of tree node pointers: for each operand, create a single-node tree and push it; for each binary operator, pop the right subtree R, pop the left subtree L, create a new operator node with children L and R, and push it back. Traversing the resulting expression tree in preorder, inorder, and postorder yields prefix, parenthesized infix, and postfix notations respectively.
typedef struct ENode {
char val;
struct ENode *left, *right;
} ENode;
ENode* newENode(char v) {
ENode *n = (ENode*)malloc(sizeof(ENode));
n->val = v; n->left = n->right = NULL;
return n;
}
ENode* buildExprTree(const char *postfix) {
ENode *st[100];
int top = -1;
for (int i = 0; postfix[i] != '\0'; i++) {
char ch = postfix[i];
ENode *n = newENode(ch);
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
n->right = st[top--];
n->left = st[top--];
}
st[++top] = n;
}
return st[top];
}Chapter 2: Binary Tree Representations and Traversals
2.1 Sequential (Array) and Linked Representations
In the sequential (array) representation, nodes are stored in a 1D array using level-order numbering starting at index 0. For any node at index : its left child is at index , its right child is at index , and its parent is at index . While array storage eliminates pointer overhead and excels for complete binary trees, a skewed tree of nodes requires array slots, wasting exponential memory.
In the linked representation, each node is a dynamically allocated structure with data, left, and right fields, consuming space strictly proportional to the actual node count regardless of tree balance.
2.2 Binary Tree Traversals: Preorder, Inorder, and Postorder
A tree traversal visits every node in the tree exactly once in time and recursion stack space. Depth-first traversals follow three canonical orderings:
- Preorder (Root → Left → Right): Visit the root, recursively traverse the left subtree, then recursively traverse the right subtree. Useful for cloning trees and generating prefix expressions.
- Inorder (Left → Root → Right): Recursively traverse the left subtree, visit the root, then recursively traverse the right subtree. On a Binary Search Tree, inorder traversal outputs all keys in sorted ascending order.
- Postorder (Left → Right → Root): Recursively traverse the left subtree, recursively traverse the right subtree, then visit the root. Essential for bottom-up evaluation of expression trees and safely deallocating all nodes of a tree.
Worked Traversal Example: Consider a binary tree with root 10, left child 5 (having children 2 and 7), and right child 20 (having right child 30). Preorder visits 10, 5, 2, 7, 20, 30. Inorder visits 2, 5, 7, 10, 20, 30. Postorder visits 2, 7, 5, 30, 20, 10.
#include <stdio.h>
#include <stdlib.h>
typedef struct TNode {
int data;
struct TNode *left;
struct TNode *right;
} TNode;
TNode* createTNode(int val) {
TNode *n = (TNode*)malloc(sizeof(TNode));
if (!n) return NULL;
n->data = val;
n->left = n->right = NULL;
return n;
}
void preorder(const TNode *root) {
if (root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(const TNode *root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void postorder(const TNode *root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int countNodes(const TNode *root) {
if (root == NULL) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int treeHeight(const TNode *root) {
if (root == NULL) return -1;
int lh = treeHeight(root->left);
int rh = treeHeight(root->right);
return 1 + (lh > rh ? lh : rh);
}Chapter 3: Binary Search Tree (BST) and Applications
3.1 BST Property, Creation, Search, and Insertion
A Binary Search Tree (BST) is a binary tree satisfying the BST ordering invariant at every node : every key in 's left subtree is strictly less than , every key in 's right subtree is strictly greater than , and both subtrees are themselves valid BSTs. A BST is created by starting with root = NULL and inserting elements one by one.
Searching starts at root: if root == NULL or root->data == key, return root; if key < root->data, search left; otherwise search right. Insertion follows the identical comparison path until reaching a NULL child pointer and attaches the new node there. Both operations run in time, where is tree height ( average/balanced, worst-case skewed when keys arrive in sorted order).
Step-by-Step Creation Trace: Inserting [50, 30, 70, 20, 40, 60, 80] into an empty BST places 50 as root; 30 < 50 goes left; 70 > 50 goes right; 20 < 50 and 20 < 30 becomes left child of 30; 40 becomes right child of 30; 60 becomes left child of 70; and 80 becomes right child of 70. An inorder traversal yields 20, 30, 40, 50, 60, 70, 80.
3.2 Deletion in a Binary Search Tree
Deleting a key from a BST must preserve the BST invariant across three structural cases:
- Case 1 — Leaf Node (0 children): Free the node and return
NULLto its parent. (e.g., deleting20simply sets30->left = NULL). - Case 2 — One Child: Bypass the node by returning its single non-null child (left or right) to its parent and freeing the deleted node.
- Case 3 — Two Children: Find the node's inorder successor (the minimum-key node in its right subtree, obtained by following
leftpointers fromroot->right). Copy the successor's key into the target node, then recursively delete the successor from the right subtree (which is guaranteed to have at most one child, reducing to Case 1 or Case 2). For example, deleting root50finds inorder successor60, replaces50with60, and deletes leaf60from the right subtree.
| Operation | Balanced BST (Average) | Skewed BST (Worst) | Sorted Array |
|---|---|---|---|
| Search | |||
| Insertion | |||
| Deletion | |||
| Sorted Traversal | (Inorder) |
TNode* searchBST(TNode *root, int key) {
while (root != NULL && root->data != key) {
root = (key < root->data) ? root->left : root->right;
}
return root;
}
TNode* insertBST(TNode *root, int key) {
if (root == NULL) return createTNode(key);
if (key < root->data) root->left = insertBST(root->left, key);
else if (key > root->data) root->right = insertBST(root->right, key);
return root;
}
TNode* findMinBST(TNode *node) {
while (node != NULL && node->left != NULL) node = node->left;
return node;
}
TNode* deleteBST(TNode *root, int key) {
if (root == NULL) return NULL;
if (key < root->data) {
root->left = deleteBST(root->left, key);
} else if (key > root->data) {
root->right = deleteBST(root->right, key);
} else {
if (root->left == NULL) {
TNode *tmp = root->right; free(root); return tmp;
}
if (root->right == NULL) {
TNode *tmp = root->left; free(root); return tmp;
}
TNode *succ = findMinBST(root->right);
root->data = succ->data;
root->right = deleteBST(root->right, succ->data);
}
return root;
}3.3 Applications of Trees
Trees are indispensable across system software: operating system file systems organize directories and files as hierarchical trees; database management systems employ self-balancing search trees (AVL trees, Red-Black trees, B+ trees) for indexing; compilers parse expressions into syntax trees; data compression algorithms (Huffman coding) construct optimal prefix trees; and artificial intelligence engines use decision trees and game-state search trees.
Chapter 4: Iterative Traversals, Level-Order Traversal & BST Diagnostics
4.1 Level-Order Traversal and Iterative Depth-First Traversals
While recursive traversals use the implicit system call stack, iterative traversals use an explicit stack or queue—essential when deep skewed trees risk overflowing the system call stack.
- Level-Order Traversal (Breadth-First): Uses a FIFO queue. Enqueue
root; while the queue is non-empty, dequeue nodecurr, printcurr->data, and enqueuecurr->leftandcurr->rightif non-null. Visits nodes level by level from top to bottom, left to right. - Iterative Inorder Traversal: Uses an explicit stack. Push left children down to
NULL, pop a node, process it, and move to its right child, repeating until bothcurr == NULLand the stack is empty. - Iterative Preorder Traversal: Push
rootonto the stack; popcurr, process it, pushcurr->right(if non-null), then pushcurr->left(if non-null) so the left child is popped first.
void levelOrder(TNode *root) {
if (root == NULL) return;
TNode *q[100];
int front = 0, rear = 0;
q[rear++] = root;
while (front < rear) {
TNode *curr = q[front++];
printf("%d ", curr->data);
if (curr->left != NULL) q[rear++] = curr->left;
if (curr->right != NULL) q[rear++] = curr->right;
}
}
void iterativeInorder(TNode *root) {
TNode *st[100];
int top = -1;
TNode *curr = root;
while (curr != NULL || top >= 0) {
while (curr != NULL) {
st[++top] = curr;
curr = curr->left;
}
curr = st[top--];
printf("%d ", curr->data);
curr = curr->right;
}
}4.2 Expression Tree Evaluation Algorithm
Once an expression tree is built from a postfix expression, evaluating it recursively takes time: if a node is a leaf (operand), return its integer value; otherwise, recursively evaluate leftVal = eval(root->left) and rightVal = eval(root->right), apply the node's operator root->val, and return the result. For the postfix string 5 3 + 8 2 - *, the root * evaluates its left subtree (5 + 3) = 8 and right subtree (8 - 2) = 6, returning 48.
4.3 BST Degeneracy and Motivation for Balanced Trees
If keys are inserted into a standard BST in strictly sorted order (e.g., 10, 20, 30, 40, 50), every node has an empty left child, degenerating the tree into a right-skewed linked list of height . In this degenerate state, search, insertion, and deletion degrade from to . Self-balancing binary search trees such as AVL trees (which enforce a height-balance factor of at every node via single and double rotations) and Red-Black trees guarantee worst-case height regardless of insertion order.
| Tree Traversal | Order of Visit | Primary Auxiliary Structure | Key Output / Property |
|---|---|---|---|
| Preorder | Root, Left, Right | Stack / Recursion | Prefix expression; tree serialization |
| Inorder | Left, Root, Right | Stack / Recursion | Sorted ascending keys on a BST |
| Postorder | Left, Right, Root | Stack / Recursion | Postfix expression; safe tree deletion |
| Level-Order | Level 0, 1, 2, ... | Queue (FIFO) | Breadth-first layer inspection |
4.4 Reconstructing a Binary Tree from Traversals
A binary tree with distinct node keys cannot be uniquely reconstructed from a single traversal alone, nor from Preorder + Postorder alone (if degree-1 nodes exist). However, Inorder + Preorder (or Inorder + Postorder) uniquely determines the entire tree structure:
- The first element of Preorder (or the last element of Postorder) identifies the root of the current subtree.
- Locating that root key inside the Inorder sequence partitions the Inorder array into all keys belonging to the left subtree (to the left of the root) and all keys belonging to the right subtree (to the right of the root).
- Recursively applying steps 1 and 2 to the left and right partitions reconstructs the exact original binary tree in naive time or with index hashing.
4.5 Worked BST Deletion Trace Across All Three Cases
Consider a BST containing keys [50, 30, 70, 20, 40, 60, 80, 65] where 50 is root, 30 has children 20, 40, and 70 has children 60 (right: 65) and 80.
- Deleting Leaf
20(Case 1): Search reaches20(both childrenNULL). Parent30->leftis set toNULLand node20is freed. - Deleting Single-Child Node
60(Case 2): Node60hasleft == NULLandright == 65. Parent70->leftis updated to point directly to65, bypassing and freeing60. - Deleting Two-Child Node
50(Case 3): Root50has both left (30) and right (70) subtrees. Its inorder successor is the minimum node in the right subtree (65). Key50is overwritten with65, and node65is deleted from the right subtree, preserving the BST invariant.
int countLeaves(const TNode *root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
return countLeaves(root->left) + countLeaves(root->right);
}
int isValidBSTUtil(const TNode *root, int minVal, int maxVal) {
if (root == NULL) return 1;
if (root->data <= minVal || root->data >= maxVal) return 0;
return isValidBSTUtil(root->left, minVal, root->data) &&
isValidBSTUtil(root->right, root->data, maxVal);
}
void mirrorTree(TNode *root) {
if (root == NULL) return;
TNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
mirrorTree(root->left);
mirrorTree(root->right);
}
void freeTree(TNode *root) {
if (root == NULL) return;
freeTree(root->left);
freeTree(root->right);
free(root);
}4.6 Summary of Tree Complexity Bounds
In any binary tree with nodes, recursive and iterative traversals require time because every node is visited once. Space complexity for DFS traversals is , ranging from on balanced trees to on skewed trees, whereas Level-Order (BFS) traversal uses queue space where is the maximum tree width.
4.7 Iterative Preorder, Postorder, and Inorder Successor in BST
Iterative Preorder traversal pushes root onto an explicit stack, pops curr, prints its key, and pushes curr->right before curr->left so the left subtree is processed first. Iterative Postorder traversal can be implemented cleanly using two stacks: stack 1 pops curr, pushes it onto stack 2, and pushes curr->left then curr->right onto stack 1; finally, popping all nodes from stack 2 emits exact Left-Right-Root postorder.
void iterativePreorder(TNode *root) {
if (root == NULL) return;
TNode *st[100];
int top = -1;
st[++top] = root;
while (top >= 0) {
TNode *curr = st[top--];
printf("%d ", curr->data);
if (curr->right != NULL) st[++top] = curr->right;
if (curr->left != NULL) st[++top] = curr->left;
}
}
TNode* inorderSuccessorBST(TNode *root, TNode *target) {
if (target->right != NULL) return findMinBST(target->right);
TNode *succ = NULL;
while (root != NULL) {
if (target->data < root->data) {
succ = root;
root = root->left;
} else if (target->data > root->data) {
root = root->right;
} else {
break;
}
}
return succ;
}4.8 Worked Numerical Example: Expression Tree Evaluation Trace
Given the arithmetic expression ((12 + 8) * (9 - 4)) / 5, its postfix form is 12 8 + 9 4 - * 5 /. Building the expression tree places / at the root with right leaf 5 and left subtree rooted at *. Evaluating bottom-up computes 12 + 8 = 20 and 9 - 4 = 5, multiplies 20 * 5 = 100, and divides 100 / 5 = 20.
4.9 Iterative Postorder Traversal and BST Range Search in C
In database indexing, a frequent query on a Binary Search Tree is a range search that prints all keys satisfying in sorted order. Using a pruned inorder traversal, we skip the left subtree whenever root->data <= L and skip the right subtree whenever root->data >= R, running in time where is the number of reported keys.
void rangePrintBST(const TNode *root, int L, int R) {
if (root == NULL) return;
if (root->data > L) rangePrintBST(root->left, L, R);
if (root->data >= L && root->data <= R) printf("%d ", root->data);
if (root->data < R) rangePrintBST(root->right, L, R);
}
TNode* lcaBST(TNode *root, int n1, int n2) {
while (root != NULL) {
if (n1 < root->data && n2 < root->data) root = root->left;
else if (n1 > root->data && n2 > root->data) root = root->right;
else return root;
}
return NULL;
}
void iterativePostorder(TNode *root) {
if (root == NULL) return;
TNode *s1[100], *s2[100];
int t1 = -1, t2 = -1;
s1[++t1] = root;
while (t1 >= 0) {
TNode *curr = s1[t1--];
s2[++t2] = curr;
if (curr->left != NULL) s1[++t1] = curr->left;
if (curr->right != NULL) s1[++t1] = curr->right;
}
while (t2 >= 0) printf("%d ", s2[t2--]->data);
}4.10 Threaded Binary Trees and Array-to-Tree Construction
In a standard linked binary tree with nodes, exactly of the child pointers are NULL. A threaded binary tree repurposes these unused NULL pointers as threads pointing to a node's inorder predecessor (via left) and inorder successor (via right), enabling inorder traversal without recursion or an explicit stack. Similarly, a complete binary tree stored in an array arr[0..n-1] can be converted to a linked tree in time by recursively linking index to (left) and (right).
TNode* buildFromArray(const int arr[], int i, int n) {
if (i >= n) return NULL;
TNode *root = createTNode(arr[i]);
root->left = buildFromArray(arr, 2 * i + 1, n);
root->right = buildFromArray(arr, 2 * i + 2, n);
return root;
}
int isIdentical(const TNode *a, const TNode *b) {
if (a == NULL && b == NULL) return 1;
if (a == NULL || b == NULL) return 0;
return (a->data == b->data) &&
isIdentical(a->left, b->left) &&
isIdentical(a->right, b->right);
}Module V: Graphs & Flexi Module Extensions
Chapter 1: Graph Terminologies and Representations
1.1 Graph Definition and Essential Terminologies
A graph is a non-linear data structure composed of a finite set of vertices (nodes) and a set of edges connecting pairs of vertices. Unlike trees, graphs impose no root-to-leaf hierarchy and may contain cycles, multiple paths between vertices, and disconnected components.
- Undirected vs. Directed Graph (Digraph): In an undirected graph, an edge is bidirectional; in a directed graph, an edge has a specific orientation from source to destination .
- Weighted Graph: Each edge carries a numerical weight or cost (such as distance, bandwidth, or travel time).
- Adjacent Vertices and Degree: Two vertices joined by an edge are adjacent. In an undirected graph, the degree of vertex is the count of incident edges, and the sum of all degrees equals (Handshaking Lemma). In a directed graph, in-degree counts incoming edges and out-degree counts outgoing edges.
- Path, Simple Path, and Cycle: A path is a sequence of vertices connected by edges. A simple path visits no vertex twice; a cycle is a closed path where the start and end vertices coincide. A Directed Acyclic Graph (DAG) contains no directed cycles.
- Connected Graph and Complete Graph: An undirected graph is connected if a path exists between every pair of vertices. A complete graph has an edge between every distinct pair of vertices, containing edges (undirected).
1.2 Graph Representations: Adjacency Matrix and Adjacency List
Two standard in-memory representations model a graph with vertices and edges:
- Adjacency Matrix: A 2D array
adj[V][V]whereadj[i][j] = 1(or edge weight ) if an edge connects vertex to , and 0 otherwise. For undirected graphs, the matrix is symmetric (adj[i][j] == adj[j][i]). Edge existence queries take time, but memory consumption is always regardless of edge count. - Adjacency List: An array of linked lists where
adj[i]stores all vertices adjacent to vertex . Memory usage is , making it vastly superior for sparse graphs ().
| Comparison Metric | Adjacency Matrix | Adjacency List |
|---|---|---|
| Space Complexity | ||
| Check Edge | ||
| List All Neighbors of | ||
| Add an Edge | (prepend to list) | |
| Optimal Graph Density | Dense graphs | Sparse graphs |
Chapter 2: Graph Traversal Algorithms (BFS and DFS)
2.1 Breadth-First Search (BFS)
Breadth-First Search (BFS) systematically explores a graph layer by layer outward from a starting vertex . Using a FIFO Queue and a boolean visited[] array, BFS marks visited and enqueues it. In each step, it dequeues a vertex , processes it, and enqueues all unvisited neighbors of , marking them visited immediately upon enqueuing so no vertex is queued twice. BFS computes shortest paths (minimum number of edges) in unweighted graphs and runs in time with adjacency lists ( with an adjacency matrix).
2.2 Depth-First Search (DFS)
Depth-First Search (DFS) plunges as deeply as possible along each branch before backtracking. Using a LIFO Stack (either explicitly or via recursion) and a visited[] array, DFS marks visited and recursively explores its first unvisited neighbor. When a vertex has no remaining unvisited neighbors, execution backtracks to the previous vertex. DFS runs in time with adjacency lists and underpins cycle detection, topological sorting, and connected-component discovery.
| Feature | Breadth-First Search (BFS) | Depth-First Search (DFS) |
|---|---|---|
| Auxiliary Data Structure | Queue (FIFO) | Stack (LIFO) or Recursion |
| Exploration Pattern | Level-by-level (wide) | Branch-by-branch (deep) |
| Shortest Path (Unweighted) | Guaranteed minimum edges | Not guaranteed |
| Time Complexity (Adj. List) | ||
| Key Applications | Shortest path, web crawling, peer discovery | Cycle detection, topological sort, maze solving |
#include <stdio.h>
#include <stdlib.h>
#define MAXV 20
typedef struct AdjNode {
int dest;
struct AdjNode *next;
} AdjNode;
typedef struct {
int V;
AdjNode *head[MAXV];
} Graph;
Graph* createGraph(int V) {
Graph *g = (Graph*)malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) g->head[i] = NULL;
return g;
}
void addEdge(Graph *g, int u, int v) {
AdjNode *n = (AdjNode*)malloc(sizeof(AdjNode));
n->dest = v; n->next = g->head[u]; g->head[u] = n;
}
void BFS(Graph *g, int start) {
int visited[MAXV] = {0}, queue[MAXV], front = 0, rear = 0;
visited[start] = 1;
queue[rear++] = start;
while (front < rear) {
int u = queue[front++];
printf("%d ", u);
for (AdjNode *p = g->head[u]; p != NULL; p = p->next) {
if (!visited[p->dest]) {
visited[p->dest] = 1;
queue[rear++] = p->dest;
}
}
}
}
void DFSUtil(Graph *g, int u, int visited[]) {
visited[u] = 1;
printf("%d ", u);
for (AdjNode *p = g->head[u]; p != NULL; p = p->next) {
if (!visited[p->dest]) DFSUtil(g, p->dest, visited);
}
}
void DFSIterative(Graph *g, int start) {
int visited[MAXV] = {0}, stack[MAXV], top = -1;
stack[++top] = start;
while (top >= 0) {
int u = stack[top--];
if (!visited[u]) {
visited[u] = 1;
printf("%d ", u);
for (AdjNode *p = g->head[u]; p != NULL; p = p->next) {
if (!visited[p->dest]) stack[++top] = p->dest;
}
}
}
}Chapter 3: Flexi Module — Circular and Header Linked Lists
3.1 Circular Linked List: Insertion and Deletion
When implementing a Circular Linked List (CLL) using a last pointer (pointing to the tail node, whose next points to the head node), both front and end insertions operate in time:
- Insert at Beginning (): If
last == NULL, setnewNode->next = newNodeandlast = newNode. Otherwise, setnewNode->next = last->nextandlast->next = newNode. - Insert at End (): Perform the same pointer link as front insertion, then additionally advance
last = newNode. - Delete from Beginning (): If
last == NULL, return. Iflast->next == last(single node), free it and setlast = NULL. Otherwise savehead = last->next, setlast->next = head->next, and freehead. - Delete from End (): Traverse from
last->nextuntil reaching the predecessorcurrwherecurr->next == last, linkcurr->next = last->next, freelast, and updatelast = curr. - Delete by Key (): Maintain
prev = *lastandcurr = (*last)->next. Advance untilcurr->data == keyor a full cycle completes. Unlinkcurr, update*lastifcurr == *last, and freecurr.
typedef struct CNode {
int data;
struct CNode *next;
} CNode;
void insertFrontCLL(CNode **last, int val) {
CNode *n = (CNode*)malloc(sizeof(CNode));
n->data = val;
if (*last == NULL) {
n->next = n;
*last = n;
} else {
n->next = (*last)->next;
(*last)->next = n;
}
}
void insertEndCLL(CNode **last, int val) {
insertFrontCLL(last, val);
if (*last != NULL) *last = (*last)->next;
}
int deleteFrontCLL(CNode **last) {
if (*last == NULL) return 0;
CNode *head = (*last)->next;
if (head == *last) {
free(head);
*last = NULL;
} else {
(*last)->next = head->next;
free(head);
}
return 1;
}
int deleteEndCLL(CNode **last) {
if (*last == NULL) return 0;
CNode *head = (*last)->next;
if (head == *last) {
free(head);
*last = NULL;
return 1;
}
CNode *curr = head;
while (curr->next != *last) curr = curr->next;
curr->next = head;
free(*last);
*last = curr;
return 1;
}
void traverseCLL(CNode *last) {
if (last == NULL) return;
CNode *curr = last->next;
do {
printf("%d -> ", curr->data);
curr = curr->next;
} while (curr != last->next);
printf("(back to head)\n");
}3.2 Header Linked Lists: Grounded and Circular
A header linked list places a permanent sentinel node—the header node—at the front of the list. Even when zero data items are stored, the header node exists, which eliminates special-case head == NULL branches during insertion and deletion. The header node's data field commonly maintains list-level metadata such as the total element count.
- Grounded Header Linked List: The final data node's
nextpointer holdsNULL. An empty list satisfiesheader->next == NULL. - Circular Header Linked List: The final data node's
nextpointer points back to theheadernode. An empty list satisfiesheader->next == header, and traversal loops fromheader->nextuntilcurr == header.
| Property | Grounded Header List | Circular Header List |
|---|---|---|
| Empty List Condition | header->next == NULL | header->next == header |
| Last Node Pointer | NULL | Points back to header |
| Traversal Stop | curr != NULL | curr != header |
| Header Metadata | Stores node count / summary | Stores node count / summary |
typedef struct HNode {
int data; /* header node stores element count */
struct HNode *next;
} HNode;
HNode* createGroundedHeader(void) {
HNode *hdr = (HNode*)malloc(sizeof(HNode));
hdr->data = 0;
hdr->next = NULL;
return hdr;
}
HNode* createCircularHeader(void) {
HNode *hdr = (HNode*)malloc(sizeof(HNode));
hdr->data = 0;
hdr->next = hdr;
return hdr;
}
void insertAfterHeader(HNode *hdr, int val) {
HNode *n = (HNode*)malloc(sizeof(HNode));
n->data = val;
n->next = hdr->next;
hdr->next = n;
hdr->data++;
}
void traverseCircularHeader(const HNode *hdr) {
for (const HNode *curr = hdr->next; curr != hdr; curr = curr->next) {
printf("%d -> ", curr->data);
}
printf("(header)\n");
}Chapter 4: Flexi Module — Applications of Graphs
Graphs provide the mathematical backbone for modeling interconnected systems across software and engineering:
- Shortest-Path Routing and GPS Navigation: Road networks and internet packet routers model intersections/routers as vertices and road segments/links as weighted edges; BFS (unweighted) and Dijkstra's algorithm (weighted) compute minimum-cost routes.
- Social Network Analysis: Users are vertices and friendships or follower links are edges; BFS discovers degrees of separation, friend recommendations, and community clusters.
- Dependency Resolution and Build Pipelines: Compilers, package managers, and project schedulers represent task prerequisites as Directed Acyclic Graphs (DAGs) and apply DFS-based topological sorting to determine valid execution order.
- Web Crawling and Search Indexing: Search engines treat web pages as vertices and hyperlinks as directed edges, using BFS/DFS crawlers to discover and rank pages.
- Telecommunications and Power Grids: Minimum Spanning Tree algorithms (Prim's and Kruskal's) connect all cities or substations with minimum total cable length without cycles.
- Deadlock Detection in Operating Systems: Resource allocation graphs model processes and system resources as vertices; detecting a cycle via DFS identifies a resource deadlock.
4.1 Step-by-Step BFS and DFS Trace on a Sample Graph
Consider an undirected graph with 5 vertices {0, 1, 2, 3, 4} and edges (0,1), (0,2), (1,3), (1,4), (2,4), starting traversal at vertex 0 (visiting neighbors in ascending numeric order).
| Step | BFS Queue State | BFS Action / Output | DFS Stack / Call State | DFS Action / Output |
|---|---|---|---|---|
| 1 | [0] | Dequeue 0, enqueue 1, 2 → Out: 0 | call(0) | Visit 0, recurse to 1 → Out: 0 |
| 2 | [1, 2] | Dequeue 1, enqueue 3, 4 → Out: 0, 1 | call(0)→call(1) | Visit 1, recurse to 3 → Out: 0, 1 |
| 3 | [2, 3, 4] | Dequeue 2 (4 already visited) → Out: 0, 1, 2 | call(0)→call(1)→call(3) | Visit 3, backtrack to 1 → Out: 0, 1, 3 |
| 4 | [3, 4] | Dequeue 3 → Out: 0, 1, 2, 3 | call(0)→call(1)→call(4) | Visit 4, recurse to 2 → Out: 0, 1, 3, 4 |
| 5 | [4] | Dequeue 4 → Final: 0, 1, 2, 3, 4 | call(0)→call(1)→call(4)→call(2) | Visit 2, unwind → Final: 0, 1, 3, 4, 2 |
4.2 Counting Connected Components and Circular List Key Deletion
To count connected components in an undirected graph, iterate over all vertices : whenever !visited[v], increment a component counter and invoke DFS (or BFS) from to mark its entire component visited. Similarly, in Circular Linked Lists, deleting an arbitrary key searches around the ring using prev and curr until curr->data == key or one full cycle completes.
int countComponents(Graph *g) {
int visited[MAXV] = {0}, components = 0;
for (int v = 0; v < g->V; v++) {
if (!visited[v]) {
components++;
DFSUtil(g, v, visited);
}
}
return components;
}
int deleteByKeyCLL(CNode **last, int key) {
if (*last == NULL) return 0;
CNode *curr = (*last)->next, *prev = *last;
do {
if (curr->data == key) {
if (curr == *last && curr->next == *last) {
free(curr); *last = NULL;
} else {
prev->next = curr->next;
if (curr == *last) *last = prev;
free(curr);
}
return 1;
}
prev = curr;
curr = curr->next;
} while (curr != (*last)->next);
return 0;
}4.3 Algorithmic Overview of Core Graph Applications
Beyond basic BFS and DFS, three classic graph algorithms power production systems: (1) Dijkstra's Shortest-Path Algorithm uses a min-priority queue to find minimum-weight paths from a source vertex in graphs with non-negative edge weights in time; (2) Topological Sorting orders vertices of a Directed Acyclic Graph (DAG) so every directed edge places before , resolving build and course prerequisites; and (3) Prim's and Kruskal's Algorithms compute Minimum Spanning Trees connecting all vertices with minimum total edge weight.
void topologicalSortKahn(int adj[MAXV][MAXV], int V) {
int indeg[MAXV] = {0}, q[MAXV], front = 0, rear = 0;
for (int u = 0; u < V; u++) {
for (int v = 0; v < V; v++) {
if (adj[u][v]) indeg[v]++;
}
}
for (int i = 0; i < V; i++) {
if (indeg[i] == 0) q[rear++] = i;
}
while (front < rear) {
int u = q[front++];
printf("%d ", u);
for (int v = 0; v < V; v++) {
if (adj[u][v] && --indeg[v] == 0) {
q[rear++] = v;
}
}
}
}
int hasCycleUndirectedDFS(Graph *g, int u, int parent, int visited[]) {
visited[u] = 1;
for (AdjNode *p = g->head[u]; p != NULL; p = p->next) {
int v = p->dest;
if (!visited[v]) {
if (hasCycleUndirectedDFS(g, v, u, visited)) return 1;
} else if (v != parent) {
return 1;
}
}
return 0;
}4.4 Complete Adjacency Matrix vs. Adjacency List Implementation Guidelines
When designing graph software, choose an Adjacency Matrix when the graph is dense (), when frequent edge-weight updates or existence queries are required, or when is small (under a few thousand vertices). Choose an Adjacency List when the graph is sparse (such as road networks, social graphs, or the World Wide Web where average vertex degree is tiny relative to ), ensuring memory scales as rather than .
4.5 Circular Header Linked List Deletion and Search in C
To complete the Flexi Module V toolkit, deletion by key in a circular header linked list starts at prev = hdr and curr = hdr->next, looping while curr != hdr. Because hdr is never deleted, there is no special head-update branch; removing any node executes prev->next = curr->next; free(curr); hdr->data--; uniformly.
HNode* searchCircularHeader(const HNode *hdr, int key) {
for (HNode *curr = hdr->next; curr != hdr; curr = curr->next) {
if (curr->data == key) return curr;
}
return NULL;
}
int deleteCircularHeader(HNode *hdr, int key) {
HNode *prev = hdr, *curr = hdr->next;
while (curr != hdr && curr->data != key) {
prev = curr;
curr = curr->next;
}
if (curr == hdr) return 0;
prev->next = curr->next;
free(curr);
hdr->data--;
return 1;
}4.6 Shortest-Path Computation in Unweighted Graphs Using BFS
Because BFS visits vertices in strictly non-decreasing order of edge distance from the source vertex , storing a dist[] array (initialized to -1, with dist[s] = 0) and setting dist[v] = dist[u] + 1 whenever an unvisited neighbor is discovered from yields the exact shortest-path hop count from to every reachable vertex in linear time.
void shortestPathBFS(Graph *g, int src, int dist[]) {
int q[MAXV], front = 0, rear = 0;
for (int i = 0; i < g->V; i++) dist[i] = -1;
dist[src] = 0;
q[rear++] = src;
while (front < rear) {
int u = q[front++];
for (AdjNode *p = g->head[u]; p != NULL; p = p->next) {
int v = p->dest;
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q[rear++] = v;
}
}
}
}4.7 Summary of Graph & Advanced Linked List Complexities
| Data Structure / Algorithm | Time Complexity | Space Complexity | Primary Engineering Use |
|---|---|---|---|
| BFS / DFS (Adjacency List) | Shortest path (unweighted), cycle check | ||
| BFS / DFS (Adjacency Matrix) | Dense graph traversal | ||
Circular List Insert Front/End (last ptr) | Round-robin scheduling | ||
| Header List Insert / Delete | front / key | Uniform sentinel-based list ops |
4.8 Bipartite Graph Checking Using BFS Two-Coloring
A graph is bipartite if its vertices can be partitioned into two disjoint sets and such that every edge connects a vertex in to one in (equivalently, the graph contains no odd-length cycles). Using BFS, we assign color 0 to the source vertex and color 1 - color[u] to every unvisited neighbor . If an already-colored neighbor has the same color as , the graph is not bipartite.
int isBipartite(Graph *g) {
int color[MAXV], q[MAXV];
for (int i = 0; i < g->V; i++) color[i] = -1;
for (int start = 0; start < g->V; start++) {
if (color[start] != -1) continue;
int front = 0, rear = 0;
color[start] = 0;
q[rear++] = start;
while (front < rear) {
int u = q[front++];
for (AdjNode *p = g->head[u]; p != NULL; p = p->next) {
int v = p->dest;
if (color[v] == -1) {
color[v] = 1 - color[u];
q[rear++] = v;
} else if (color[v] == color[u]) {
return 0;
}
}
}
}
return 1;
}University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 2 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Introduction to Data Structures (University of Kerala BCA Sem 2)
Introduction to Data Structures (UK2DSCCAP103 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in introduction to data structures. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Introduction to Data Structures Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Data Structures, Arrays, Searching & Sorting
A data structure is a systematic, formal mechanism for organizing, storing, and managing data in computer memory so that retrieval, insertion, deletion, modification, and aggregation operations execute efficiently. Whereas a primitive data type (such as int, char, float, or double ) represents a single atomic value, a data structure establishes both logical and physical relationships among a collection of data elements.
Linked Lists
A linked list is a linear, dynamic data structure formed by chaining independent memory blocks called nodes. Unlike arrays, which require a single contiguous block of memory, linked list nodes can be scattered arbitrarily across the system heap. Each node encapsulates two components: a data field (one or more payload attributes) and one or more link (pointer) fields storing the physical memory address of adjacent nodes.
Stack & Queue
A stack is a linear abstract data type governed by the Last-In, First-Out (LIFO) access policy: the most recently inserted element is always the first element removed. All insertions and deletions are restricted to a single end called the top. Attempting to push onto a full fixed-size stack causes Stack Overflow, while attempting to pop or peek an empty stack causes Stack Underflow. In an array-based stack, a fixed array items[MAX] and an integer index top (initialized to -1 ) track the state.
Trees & Binary Search Trees
A tree is a non-linear, acyclic, hierarchical data structure consisting of a finite set of nodes connected by directed edges. One node is designated as the root (having no parent), and every remaining node has exactly one parent node. A tree with N nodes always contains exactly N − 1 edges. A binary tree is a specialized tree in which every node has at most two children, explicitly distinguished as the left child and the right child. Key mathematical properties of binary trees govern their capacity and balance:
Graphs & Flexi Module Extensions
A graph G = ( V, E ) is a non-linear data structure composed of a finite set of vertices (nodes) V and a set of edges E connecting pairs of vertices. Unlike trees, graphs impose no root-to-leaf hierarchy and may contain cycles, multiple paths between vertices, and disconnected components. Two standard in-memory representations model a graph with V vertices and E edges:
Core Curriculum & Key Topics
- Foundations and Classification of Data Structures
- 1 Definition, Abstraction, and Role of Data Structures
- 2 Classification of Data Structures
- 3 Fundamental Operations and Real-World Applications
- Single-Dimensional Arrays and Memory Representation
- 1 Concept and Contiguous Memory Model
- 2 Array Operations: Traversal, Insertion, Deletion, and Merging
- Searching Algorithms
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of introduction to data structures.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Introduction to Data Structures
The evaluation framework for Introduction to Data Structures (UK2DSCCAP103) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK2DSCCAP103 (Introduction to Data Structures) examination: 1. Draw Clear Diagrams & Step-by-Step Traces: Illustrate trees, graphs, ER schemas, normalization tables, or ML pipeline diagrams neatly alongside dry-run traces. 2. State Complexity & Mathematical Formulas Explicitly: Include time/space complexity (Big-O notation), SQL query syntax, or model evaluation metrics (precision, recall, accuracy) accurately. 3. Compare Algorithms & Models in Tables: Use structured comparison tables (e.g., supervised vs. unsupervised, BFS vs. DFS, B-Tree vs. B+ Tree) for Part B analytical questions. 4. Allocate Time Strategically: Dedicate 25 minutes to Part A definitions, 50 minutes to Part B derivations and query/algorithm traces, and 75 minutes to Part C comprehensive problems.
Exam Preparation & Study Guides — Introduction to Data Structures
What is Data Structure Definition and Abstraction and why is it important in Introduction to Data Structures?
A data structure is a systematic method of organizing, storing, and managing data in computer memory so operations execute efficiently. Every data structure pairs an Abstract Data Type (ADT), which defines the mathematical model and valid operations, with a concrete in-memory implementation.
What is Binary Search Complexity and why is it important in Introduction to Data Structures?
Halves the search space at every step, achieving O(1) best case, O(log n) average and worst cases, and O(1) space iteratively (O(log n) stack space recursively).
What is Traversing SLL and why is it important in Introduction to Data Structures?
Initializes curr = head and advances curr = curr->next until curr == NULL in O(n) time.
What is Reverse Polish (Postfix) Notation and why is it important in Introduction to Data Structures?
Operator follows operands (e.g., A B +); requires no parentheses and evaluates in a single left-to-right stack scan.
What is Linked Representation and why is it important in Introduction to Data Structures?
Each heap node stores data, left pointer, and right pointer, adapting to arbitrary shapes in O(n) space.
What is the official course code and credit structure for Introduction to Data Structures at University of Kerala?
Introduction to Data Structures carries the official course code UK2DSCCAP103 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Introduction to Data Structures?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Introduction to Data Structures (UK2DSCCAP103) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 2 Subjects
Browse study notes for other courses in BCA Sem 2:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.