Btech 3rd Sem — Data Structures Solved Paper
- Attempt any five questions. All questions carry equal marks (14 each).
- Marks of every part are shown beside the question; answers are written to that length: definition → working/algorithm → example/diagram → conclusion.
- In case of any doubt, the English version of the question is final.
Question-wise topics
| Q.No. | Topics asked |
|---|---|
| Q1 | Abstract data types; linked list and its operations |
| Q2 | Stack vs queue; C program infix → postfix |
| Q3 | Circular linked list insert/delete algorithms; BST traversals |
| Q4 | AVL tree insertion (12 keys) and deletion of 18, 2, 30 |
| Q5 | Heap and its operations; merge sort simulation |
| Q6 | BFS vs DFS; Kruskal's algorithm |
| Q7 | Shell sort simulation; sequential search |
| Q8 | Short notes: stack using linked list, indexing, B-tree, priority queue |
Example: a user of a Stack ADT only knows push, pop, peek, isEmpty; whether it is implemented by an array or a linked list is hidden (data abstraction and encapsulation).
| ADT | Values | Main operations |
|---|---|---|
| List | ordered sequence of elements | insert, delete, find, get(i), length |
| Stack | sequence with one open end (top) — LIFO | push, pop, peek/top, isEmpty, isFull |
| Queue | sequence with two ends (front, rear) — FIFO | enqueue, dequeue, front, isEmpty |
| Deque | insert/delete at both ends | insertFront, insertRear, deleteFront, deleteRear |
| Priority Queue | elements with priorities | insert, deleteMax/deleteMin |
| Tree / BST | hierarchical nodes | insert, delete, search, traverse |
| Graph | vertices and edges | addVertex, addEdge, BFS, DFS |
| Set / Map (Dictionary) | unique keys / key–value pairs | insert, delete, search (lookup) |
Advantages: implementation can change without affecting user programs, code reuse, easier correctness proofs. Each ADT may have several implementations, e.g. List by array or linked list, Priority Queue by heap.
Operations (with C fragments)
1. Traversal — visit every node: p = start; while (p != NULL) { printf("%d ", p->data); p = p->next; }
2. Insertion at beginning — t->next = start; start = t; (O(1)). Inserting 5 → 5 → 10 → 20 → 30.
3. Insertion at end — move to last node p, then p->next = t; t->next = NULL; (O(n)). Inserting 40 → 10 → 20 → 30 → 40.
4. Insertion after a given node / at position k — t->next = p->next; p->next = t;
5. Deletion — first node: t = start; start = start->next; free(t);; a node after p: t = p->next; p->next = t->next; free(t);. Deleting 20 → 10 → 30.
6. Searching — compare each node's data with the key until found or NULL (O(n)).
7. Others — counting nodes, reversing the list, concatenation, sorting.
Types
- Singly linked list (one pointer per node)
- Doubly linked list (prev and next pointers)
- Circular linked list (last node points to first)
- Header linked list (special header node)
| Basis | Stack | Queue |
|---|---|---|
| Principle | LIFO — Last In First Out | FIFO — First In First Out |
| Ends used | One end (TOP) for both insertion and deletion | Insertion at REAR, deletion at FRONT |
| Insertion | PUSH | ENQUEUE |
| Deletion | POP | DEQUEUE |
| Pointers | One pointer: top | Two pointers: front and rear |
| Empty condition | top = −1 | front = −1 (or front > rear) |
| Full condition (array) | top = MAX − 1 | rear = MAX − 1 (linear) / (rear+1) % MAX = front (circular) |
| Variants | — | Circular queue, deque, priority queue |
| Real-life example | Pile of plates, undo button | Ticket counter line, printer queue |
| Applications | Recursion, expression evaluation, backtracking, DFS | CPU scheduling, buffering, BFS, I/O requests |
If 10, 20, 30 are inserted in that order, a stack removes 30 first whereas a queue removes 10 first.
Idea: operands go directly to the output; operators wait on a stack until an operator of lower precedence (or a right parenthesis / end of input) arrives.
Algorithm POLISH(Q, P) — infix Q to postfix P using a stack
- Push “(” onto STACK and add “)” to the end of Q.
- Scan Q from left to right and repeat steps 3–6 for each symbol until the STACK is empty:
- If an operand is found, add it to P.
- If a left parenthesis is found, push it onto STACK.
- If an operator ⊗ is found: (a) repeatedly pop from STACK and add to P each operator on the top which has the same or higher precedence than ⊗ (for right-associative ^/$ only higher); (b) push ⊗ onto STACK.
- If a right parenthesis is found: (a) repeatedly pop from STACK and add to P each operator until a left parenthesis is found; (b) remove the left parenthesis (do not add it to P).
- Exit.
| Operator | Precedence | Associativity |
|---|---|---|
| ^ or $ (exponent) | 3 (highest) | Right to left |
| *, /, % | 2 | Left to right |
| +, − | 1 (lowest) | Left to right |
C program
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char c) { stack[++top] = c; }
char pop(void) { return stack[top--]; }
char peek(void) { return stack[top]; }
int prec(char c) {
if (c == '^' || c == '$') return 3;
if (c == '*' || c == '/' || c == '%') return 2;
if (c == '+' || c == '-') return 1;
return 0;
}
int main(void) {
char infix[MAX], postfix[MAX];
int k = 0;
printf("Enter infix expression: ");
scanf("%99s", infix);
for (int i = 0; infix[i] != '\0'; i++) {
char c = infix[i];
if (isalnum((unsigned char)c))
postfix[k++] = c; /* operand -> output */
else if (c == '(')
push(c);
else if (c == ')') {
while (top != -1 && peek() != '(')
postfix[k++] = pop();
pop(); /* discard '(' */
} else { /* operator */
while (top != -1 && peek() != '(' &&
(prec(peek()) > prec(c) ||
(prec(peek()) == prec(c) && c != '^' && c != '$')))
postfix[k++] = pop();
push(c);
}
}
while (top != -1) postfix[k++] = pop();
postfix[k] = '\0';
printf("Postfix expression: %s\n", postfix);
return 0;
}Sample run: input A+(B+D)/E-F*(G+H/K) → output ABD+E/+FGHK/+*-; input A+B-C*D*E$F$G → output AB+CD*EFG$$*-.
Time complexity O(n) — each symbol is pushed and popped at most once.
- No NULL link — from any node every other node can be reached.
- Traversal stops when we come back to the starting node (do … while loop).
- Uses: round-robin CPU scheduling, circular buffers/queues, multiplayer turn games, repeating playlists.
- Variants: circular singly linked list and circular doubly linked list.
Algorithm: insert at beginning (LAST pointer)
- Create node T; T→info = ITEM.
- If LAST = NULL: LAST = T; T→next = T; exit.
- T→next = LAST→next (old first).
- LAST→next = T. Exit.
Algorithm: insert at end
- Insert T at the beginning as above.
- LAST = T (the new node becomes the last). Exit.
Algorithm: delete node with key ITEM
- If LAST = NULL → underflow, exit.
- PREV = LAST, CUR = LAST→next.
- Repeat until CUR→info = ITEM or the whole circle is scanned: PREV = CUR, CUR = CUR→next.
- If not found → print message, exit.
- If CUR = PREV (only node): LAST = NULL.
- Else PREV→next = CUR→next; if CUR = LAST then LAST = PREV.
- Free CUR. Exit.
Example: start with 10 → 20 → 30 (circular). Insert 5 at beginning → 5 → 10 → 20 → 30 → back to 5; insert 40 at end → … 30 → 40 → back to 5; delete 20 → 5 → 10 → 30 → 40 → back to 5.
All insertions at the ends are O(1) because LAST gives direct access to both the last and the first node; deletion of an arbitrary key is O(n).
Traversal means visiting every node exactly once. The three depth-first traversals differ in when the root (N) is visited relative to the left (L) and right (R) subtrees:
Recursive algorithms
void inorder(struct node *t) { /* L N R */
if (t != NULL) {
inorder(t->left);
printf("%d ", t->data);
inorder(t->right);
}
}
void preorder(struct node *t) { /* N L R */
if (t != NULL) {
printf("%d ", t->data);
preorder(t->left);
preorder(t->right);
}
}
void postorder(struct node *t) { /* L R N */
if (t != NULL) {
postorder(t->left);
postorder(t->right);
printf("%d ", t->data);
}
}| Traversal | Order | Result for the tree above | Use |
|---|---|---|---|
| Inorder | Left → Root → Right | 20 30 40 50 60 70 80 | Gives keys in sorted order for a BST |
| Preorder | Root → Left → Right | 50 30 20 40 70 60 80 | Copying a tree, prefix expression |
| Postorder | Left → Right → Root | 20 40 30 60 80 70 50 | Deleting a tree, postfix expression |
| Level order (BFS) | Level by level using a queue | 50 30 70 20 40 60 80 | Printing level-wise |
Inorder trace: inorder(50) → inorder(30) → inorder(20) prints 20 → prints 30 → inorder(40) prints 40 → back, print 50 → right subtree gives 60 70 80. Each traversal is O(n) time and O(h) stack space (h = height).
The orange ring marks the key just inserted; the note under each tree gives the imbalance found and the rotation used.
Deletions
Operations
- Insert (heapify-up / percolate up): place the new key at the next free position (end of array) and swap it with its parent while it is larger than the parent. O(log n).
- Delete (delete-max): remove the root, move the last element to the root and swap it with the larger child while it is smaller (heapify-down). O(log n).
- Build-heap: heapify-down every internal node from ⌊n/2⌋ − 1 down to 0. O(n).
- Peek (find-max): return the root. O(1).
Example — insert 10, 20, 15, 30, 40 into an empty max-heap
Insert 30: placed as child of 10 → 30 > 10 swap → 30 > 20 swap → becomes root. Insert 40: child of 20 → swap with 20 → swap with 30 → root.
Delete-max
Merge sort is a divide-and-conquer algorithm: (1) divide the array into two halves, (2) conquer — sort each half recursively, (3) combine — merge the two sorted halves into one sorted array.
void mergeSort(int a[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
merge(a, low, mid, high); /* merge a[low..mid] and a[mid+1..high] */
}
}Divide phase
| Level | Sub-arrays |
|---|---|
| 0 | 305678991243102485 |
| 1 | 3056789912 43102485 |
| 2 | 305678 9912 4310 2485 |
| 3 | 3056 78 99 12 43 10 24 85 |
| 4 | 30 56 78 99 12 43 10 24 85 |
Merge (conquer) phase
| Step | Left | Right | Merged |
|---|---|---|---|
| 1 | 30 | 56 | 3056 |
| 2 | 3056 | 78 | 305678 |
| 3 | 99 | 12 | 1299 |
| 4 | 305678 | 1299 | 1230567899 |
| 5 | 43 | 10 | 1043 |
| 6 | 24 | 85 | 2485 |
| 7 | 1043 | 2485 | 10244385 |
| 8 | 1230567899 | 10244385 | 101224304356788599 |
Both BFS and DFS are graph traversal techniques that visit every vertex reachable from a start vertex exactly once; they differ in the order of visiting.
| Basis | BFS (Breadth First Search) | DFS (Depth First Search) |
|---|---|---|
| Strategy | Level by level — all neighbours first | Goes deep along one path, then backtracks |
| Data structure | Queue (FIFO) | Stack (LIFO) / recursion |
| Shortest path | Finds shortest path (fewest edges) in unweighted graphs | Does not guarantee shortest path |
| Memory | Stores a whole level — more memory for wide graphs | Stores one path — less memory (O(height)) |
| Traversal tree | Wide and short | Narrow and deep |
| Time complexity | O(V + E) list / O(V²) matrix | O(V + E) list / O(V²) matrix |
| Backtracking | Not used | Used |
| Applications | Shortest path, peer-to-peer networks, web crawlers, bipartite check, level order | Cycle detection, topological sort, connected components, maze / puzzle solving |
Example (graph A–B, A–C, B–D, B–E, C–F): BFS from A = A B C D E F (level-wise); DFS from A = A B D E C F (depth-wise).
Kruskal's algorithm
- Sort all edges in non-decreasing order of weight.
- Start with a forest in which every vertex is a separate tree (T = ∅).
- Take the next smallest edge (u, v): if u and v are in different trees (no cycle is formed), add it to T and merge the two trees (union–find); otherwise reject it.
- Repeat until T has V − 1 edges.
Time: O(E log E) for sorting + nearly O(E) for union–find.
Edges sorted by weight: 1–2(3), 0–4(4), 2–4(5), 1–4(6), 3–4(7), 0–1(8), 2–3(9).
| Step | Edge | Weight | Action |
|---|---|---|---|
| 1 | 1–2 | 3 | Accept ✔ |
| 2 | 0–4 | 4 | Accept ✔ |
| 3 | 2–4 | 5 | Accept ✔ |
| 4 | 1–4 | 6 | Reject ✘ (forms cycle) |
| 5 | 3–4 | 7 | Accept ✔ |
Shell sort (Donald Shell, 1959) is a generalisation of insertion sort. Elements that are gap positions apart are compared and sorted (gap-insertion sort); the gap is reduced (n/2, n/4, …, 1). Large early moves remove far-away disorder, so the final insertion sort (gap 1) has very little work left.
void shellSort(int a[], int n) {
for (int gap = n / 2; gap > 0; gap /= 2)
for (int i = gap; i < n; i++) {
int temp = a[i], j;
for (j = i; j >= gap && a[j - gap] > temp; j -= gap)
a[j] = a[j - gap];
a[j] = temp;
}
}n = 8, so gaps are 4, 2, 1. Each sub-list (elements gap apart) is sorted:
| Pass | Sub-lists after sorting | Array after the pass |
|---|---|---|
| Initial | — | 3533421014192744 |
| gap = 4 | (14, 35); (19, 33); (27, 42); (10, 44) | 1419271035334244 |
| gap = 2 | (14, 27, 35, 42); (10, 19, 33, 44) | 1410271935334244 |
| gap = 1 | (10, 14, 19, 27, 33, 35, 42, 44) | 1014192733354244 |
gap 4: pairs (35,14), (33,19), (42,27), (10,44) are compared → 14, 19, 27 move left. gap 2: [14, 27, 35, 42] and [19, 10, 33, 44] → [10, 19, 33, 44]. gap 1: ordinary insertion sort on a nearly sorted array.
Sequential (linear) search compares the key with each element one by one from the first position until a match is found or the list ends. It works on unsorted data.
int linearSearch(int a[], int n, int key) {
for (int i = 0; i < n; i++)
if (a[i] == key)
return i; /* found at index i */
return -1; /* not found */
}Array: 42136146291822817710 (indices 0–10). No key is specified, so we search for 22 (present) and 50 (absent).
Search key = 22
| Index i | a[i] | Comparison |
|---|---|---|
| 0 | 4 | 22 = 4 ? No |
| 1 | 21 | 22 = 21 ? No |
| 2 | 36 | 22 = 36 ? No |
| 3 | 14 | 22 = 14 ? No |
| 4 | 62 | 22 = 62 ? No |
| 5 | 91 | 22 = 91 ? No |
| 6 | 8 | 22 = 8 ? No |
| 7 | 22 | 22 = 22 ? Yes — found |
Search key = 50
50 is compared with all 11 elements (4, 21, 36, 14, 62, 91, 8, 22, 81, 77, 10) — no match → return −1 after 11 comparisons.
| Case | Comparisons | Complexity |
|---|---|---|
| Best (key at first position) | 1 | O(1) |
| Average | (n + 1)/2 | O(n) |
| Worst (last / absent) | n | O(n) |
(i) Stack using linked list
In the linked representation each stack element is a node; TOP points to the first node. PUSH and POP are done at the beginning of the list, so both are O(1) and there is no fixed size (overflow only when memory is exhausted).
Algorithm PUSH(TOP, ITEM)
- Allocate a new node NEW; if allocation fails → print “Overflow” and exit.
- NEW→INFO = ITEM.
- NEW→LINK = TOP.
- TOP = NEW.
- Exit.
Algorithm POP(TOP)
- If TOP = NULL → print “Underflow” and exit.
- ITEM = TOP→INFO; TEMP = TOP.
- TOP = TOP→LINK.
- Free TEMP; return ITEM.
- Exit.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *top = NULL;
void push(int x) {
struct node *t = (struct node *)malloc(sizeof(struct node));
if (t == NULL) { printf("Stack Overflow (heap full)\n"); return; }
t->data = x;
t->next = top; /* new node points to old top */
top = t; /* new node becomes top */
}
int pop(void) {
if (top == NULL) { printf("Stack Underflow\n"); return -1; }
struct node *t = top;
int x = t->data;
top = top->next;
free(t);
return x;
}
int main(void) {
push(10); push(20); push(30);
printf("Popped %d\n", pop());
printf("Popped %d\n", pop());
return 0;
}Output: Popped 30, Popped 20.
(ii) Indexing
- Primary index: on the ordering key of a sorted file — one entry per block (sparse).
- Secondary index: on a non-ordering field — one entry per record (dense).
- Clustering index: on a non-key ordering field.
- Multilevel index / tree index: an index on the index — implemented by B-trees and B+ trees; search cost O(log n) disk accesses.
- Indexed sequential (ISAM) files: records stored sequentially plus an index for direct access.
Example: a student file sorted by roll number with an index entry for every 100th record — to find roll 457, look up index entry 400 and scan only that block.
(iii) B tree
1. every node has at most m children and m − 1 keys (kept in sorted order);
2. every node except the root has at least ⌈m/2⌉ children (⌈m/2⌉ − 1 keys);
3. the root has at least 2 children if it is not a leaf;
4. all leaves are at the same level;
5. keys in a node separate the keys of its subtrees (like a BST).
- Insertion: insert into the proper leaf; if it overflows (m keys), split it — the median key moves up to the parent (splits may propagate to the root, increasing height).
- Deletion: remove the key; if a node underflows, borrow from a sibling or merge with it.
- Advantages: height is O(logm n) — very few disk accesses because each node holds many keys (one node = one disk block).
(iv) Priority queue
- Types: ascending (min) priority queue — smallest key removed first; descending (max) priority queue — largest key removed first.
- Implementations: unsorted array/list (insert O(1), delete O(n)); sorted list (insert O(n), delete O(1)); binary heap (both O(log n)) — the usual choice.
- Applications: CPU process scheduling, Dijkstra's shortest path, Prim's MST, Huffman coding, event-driven simulation.
Example: jobs (P2, 5), (P1, 9), (P3, 2) inserted in a max priority queue are served P1, P2, P3.