Data Structures Assignment
---
Q1. Algorithm to Implement Stack Using Queue
Answer:
Concept: Stack follows LIFO (Last In First Out), Queue follows FIFO (First In First Out). We can use
two queues to simulate stack behavior.
Algorithm:
Initialization:
- Create two empty queues q1 and q2.
Push(x):
1. Enqueue x into q2.
2. Move all elements from q1 to q2.
3. Swap the names of q1 and q2.
Pop():
1. If q1 is empty, return error.
2. Dequeue and return element from q1.
Top():
1. Return front element of q1.
Pseudocode:
Function PUSH(x):
Enqueue x into q2
While q1 not empty:
Enqueue Dequeue(q1) into q2
Swap q1 and q2
Function POP():
If q1 is empty:
return error
return Dequeue(q1)
Function TOP():
return Front(q1)
Example:
- PUSH(10) -> PUSH(20) -> PUSH(30) -> POP() -> TOP()
Final stack elements: 20, 10
---
Q2. Algorithm for Postfix Evaluation (with Example)
Answer:
Concept: Postfix has operators after operands. No parentheses needed.
Algorithm:
1. Create an empty stack.
2. Scan the expression left to right.
3. If operand, push to stack.
4. If operator, pop two elements, apply operation, push result back.
5. Final element on stack is result.
Example:
Evaluate: 6 2 3 + - 3 8 2 / + *
Answer = 7
---
Q3. What is Stack? How it checks expression parenthesis correctness?
Answer:
Stack:
- Linear data structure, LIFO (Last In First Out).
Checking Parentheses:
- Use stack to track opening brackets.
Example 1 (Balanced):
Expression: ( [ { } ] )
Example 2 (Not Balanced):
Expression: ( [ { ] } )
---
Q4. Circular Queue with C/C# Functions for Insertion and Deletion
Answer:
Circular Queue:
- Queue where end connects back to start.
C Functions:
Enqueue:
void enqueue(int value) {...}
Dequeue:
void dequeue() {...}
Key Conditions:
- Queue full: (rear+1)%size == front
- Queue empty: front == -1
---
Q5. Infix to Postfix Conversion for A+B/C(D+E)-F
Answer:
Fixed Expression: A + (B / C) * (D + E) - F
Final Postfix Expression:
ABC/DE++F-
---
End of Assignment