Ds Ans 2
Ds Ans 2
Summary
Linear Data Structures → Single level of elements (e.g., Array, Stack, Queue).
Non-Linear Data Structures → Multiple levels or interconnections (e.g., Tree,
Graph).
Ans: An Abstract Data Type (ADT) is a logical description of a data structure that defines the
operations that can be performed on it, without specifying how these operations are implemented.
1. List ADT
Abstract Data Types (ADTs) define a set of operations that can be performed on them,
without specifying the internal implementation. Below are the common ADT operations
along with examples:
1. List ADT
Operations
A Stack follows the LIFO principle (Last-In, First-Out), meaning elements are added and
removed from the top.
Operations
A Queue follows the FIFO principle, meaning elements are added at the rear and removed
from the front.
Operations
Operations
A Priority Queue is a queue where elements are removed based on priority rather than order
of insertion.
Operations
6. Set ADT
Operations
Operations
8. Graph ADT
Operations
4.Define stack
A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle,
meaning the last element added to the stack is the first one to be removed.
Characteristics of a Stack
5.operations of stack
Applications of Stack
A stack is a LIFO (Last In, First Out) data structure widely used in programming and
computing. Below are some key applications of stacks:
When a function is called, the return address and local variables are pushed onto
the stack.
When the function finishes, its data is popped from the stack.
Example: In recursive function calls, each function call is stacked until the base case
is reached.
void recursiveFunction(int n) {
if (n == 0) return;
printf("Calling %d\n", n);
recursiveFunction(n - 1);
}
Each recursive call is pushed onto the stack until n == 0, then calls are popped.
Back Button: When a user visits a page, it is pushed onto a stack. Clicking "Back"
pops the last visited page.
Forward Button: The popped page is pushed onto another stack.
🔹 Example
User visits: A → B → C
Click "Back" → C is popped → User is on B
Click "Forward" → C is pushed back → User is on C
Used in compilers to check balanced brackets, e.g., {[()]} is valid, but {[)]} is
not.
#include <stdio.h>
#include <stdbool.h>
#define MAX 100
char stack[MAX];
int top = -1;
int main() {
char expr[] = "{[()]}";
printf(isBalanced(expr) ? "Balanced\n" : "Not Balanced\n");
}
Used in graph algorithms like Depth-First Search (DFS), where nodes are pushed
and popped.
Backtracking uses a stack to explore possible solutions. If a wrong path is taken, the
stack pops back to the previous step.
🔹 Example:
Example:
Postfix: 5 3 + 8 * → (5 + 3) * 8 = 64
The stack stores numbers and operators to compute the result.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char expr[] = "53+8*";
printf("Result: %d\n", evaluatePostfix(expr)); // Output: 64
}
Application Description
Expression Evaluation Converts and evaluates infix, prefix, and postfix expressions.
Function Call Stack Manages function calls and recursion.
Undo/Redo Operations Used in text editors, graphics software, and word processors.
Browser History Tracks visited web pages using a back-and-forward system.
Balanced Parentheses Checks if expressions have correct {}, [], ().
Graph Traversal (DFS) Uses stack-based depth-first search.
Memory Management Used in stack-based memory allocation.
Backtracking Solves problems like mazes, Sudoku, and puzzles.
Postfix Evaluation Evaluates mathematical expressions efficiently.
Final Thoughts
Stacks are powerful and versatile data structures used in algorithms, system design, and
real-world applications like compilers, operating systems, and games.
A stack follows the LIFO (Last In, First Out) principle, meaning the last inserted element
is the first to be removed.
Below are the algorithms for inserting (Push) and deleting (Pop) an element from a stack
using an array implementation.
1. PUSH Operation (Insertion into Stack)
Definition: The Push operation adds an element to the top of the stack.
Step-by-Step Process
1. Check Overflow:
o If top == MAX - 1, the stack is full (Overflow Condition).
2. Increment Top:
o Increase top by 1 to point to the next position.
3. Insert Element:
o Assign stack[top] = value.
4. End Operation.
Algorithm (Pseudocode)
PUSH(stack, top, MAX, value)
1. IF top == MAX - 1 THEN
PRINT "Stack Overflow"
RETURN
2. top = top + 1
3. stack[top] = value
4. PRINT "Element Pushed"
5. RETURN
Example Execution
Definition: The Pop operation removes an element from the top of the stack.
Algorithm: Pop (Delete from Stack)
Step-by-Step Process
1. Check Underflow:
o If top == -1, the stack is empty (Underflow Condition).
2. Retrieve Element:
o Store stack[top] in a variable.
3. Decrease Top:
o Reduce top by 1 to remove the element.
4. Return the Removed Element.
Algorithm (Pseudocode)
POP(stack, top)
1. IF top == -1 THEN
PRINT "Stack Underflow"
RETURN NULL
2. element = stack[top]
3. top = top - 1
4. RETURN element
Example Execution
Initial Stack
Top → 2
Stack: | 30 | <-- Top
| 20 |
| 10 |
Pop() → Removes 30
Top → 1
Stack: | 20 | <-- New Top
| 10 |
Pop() → Removes 20
Top → 0
Stack: | 10 |
Pop() → Removes 10
Top → -1 (Stack is Empty)
Pop() → Stack Underflow!
Error: Stack is Empty (Underflow)
typedef struct {
int items[MAX];
int top;
} Stack;
// Initialize Stack
void init(Stack *s) {
s->top = -1;
}
// Main Function
int main() {
Stack s;
init(&s);
push(&s, 10);
push(&s, 20);
push(&s, 30);
return 0;
}
Push() O(1)
Pop() O(1)
Peek() O(1)
Each operation in a stack runs in constant time O(1), making it an efficient data structure.
6. Conclusion
10.define queueu
A queue is a linear data structure that follows the FIFO (First In, First Out) principle,
meaning the element inserted first is removed first.
plaintext
CopyEdit
Enqueue(queue, item):
IF rear == size - 1 THEN
PRINT "Queue Overflow"
RETURN
END IF
IF front == -1 THEN // First element insertion
front = 0
END IF
rear = rear + 1
queue[rear] = item
PRINT "Element Inserted"
END
14.circular queue
A Circular Queue is a linear data structure that follows the FIFO (First In, First Out)
principle but connects the last position back to the first position to form a circular
arrangement.
This eliminates the problem of wasted space in a regular queue when elements are dequeued.
. Enqueue Algorithm
2. Dequeue Algorithm
15.
Ans:
A priority queue is a special type of queue where each element is assigned a priority. The
element with the highest priority is dequeued (removed) first, regardless of the order in
which it was enqueued.
If two elements have the same priority, they follow the FIFO (First-In, First-Out) order.
A priority queue can be implemented using an array, linked list, binary heap, or balanced
tree.
Here is an example of a priority queue with different elements and their assigned priorities:
Priority Queue
+----+--------+------------+
| No | Item | Priority |
+----+--------+------------+
| 1 | TaskA | 3 |
| 2 | TaskB | 1 |
| 3 | TaskC | 4 |
| 4 | TaskD | 2 |
+----+--------+------------+
Implementation Methods
1. Unsorted Array → Insert at the end, find the highest priority during dequeue (O(n)).
2. Sorted Array → Insert in sorted order (O(n)), dequeue in O(1).
3. Linked List → Similar to arrays but with dynamic memory allocation.
4. Binary Heap (Efficient) → Insert and remove in O(log n) time.
#define SIZE 5
struct PriorityQueue {
int item;
int priority;
} queue[SIZE];
int count = 0;
int i = count - 1;
// Insert in sorted order (Descending priority)
while (i >= 0 && queue[i].priority < priority) {
queue[i + 1] = queue[i];
i--;
}
display();
dequeue();
display();
enqueue(60, 4);
display();
return 0;
}
📌 How it works:
📌 How it works:
📌 How it works:
In hospitals, critical patients are treated first, even if others arrived earlier.
Example: A heart attack patient is treated before a minor injury.
🏥 Real-world example: Hospital emergency departments.
📌 How it works:
📌 How it works:
📌 How it works:
In stock trading, high-priority orders (large volume, high price) are processed first.
Buy/sell orders are queued based on priority.
📈 Real-world example: New York Stock Exchange (NYSE), Nasdaq.
📌 How it works:
Higher priority is given to business class and frequent flyers over economy
passengers.
Airline booking systems maintain a priority queue for ticket upgrades and waiting
lists.
✈ Real-world example: Delta, Emirates airline reservations.
9. Operating System Interrupt Handling
📌 How it works:
📌 How it works:
In office printers, documents are queued with priority levels (urgent documents print
first).
🖨 Real-world example: Office printer queues.