Top Banner Ad

ACS201 — Unit 3: Stack and Queue

Table of Contents (15 sections)

ACS201 · Essentials of Data Structures · Unit 3

Stack and Queue

Unit Scope & Exam Weightage: This unit studies ordered access structures: Stack — LIFO, push, pop, peek, implementation using array in C/Python, its applications balanced parentheses check and function call stack, then Queue — FIFO, enqueue, dequeue, implementation using array in C/Python, print spooler, task scheduling queue and Polish Notation. The solutions file has only generic 2026-27 model-paper templates, so the worked problems below are labelled predicted and come from the exact syllabus items and assignment traces.


Front Page: Importance-Wise Topic Roadmap (Predicted from Syllabus)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Stack — LIFO / push / pop / peek / implementation using array in C/Python 0 real PYQs predicted 7m + 2m Predicted Program
2 Application: balanced parentheses check 0 real PYQs predicted 7m Predicted Trace
3 Queue — FIFO / enqueue / dequeue / implementation using array in C/Python 0 real PYQs predicted 7m + 2m Predicted Program
4 Application: print spooler / task scheduling queue 0 real PYQs predicted 7m Predicted Application
5 function call stack (concept) 0 real PYQs predicted 2m + 5m Predicted Concept
6 Polish Notation Real connect: Ctrl+Z = Stack 0 real PYQs predicted 5m Predicted Numerical
7 WhatsApp delivery = Queue / Python error traceback IS a call stack / CPU scheduling = queue integrated in #1–#4 — Real Connect
8 Stack and Queue (unit title/topic) integrated throughout — Unit Frame

2-Hour Last-Night Survival Checklist:

  1. Stack rule: LIFO—last in, first out. push increments top then writes; pop reads s[top] then decrements; peek reads s[top] without changing top. Check overflow at top == MAX-1 and underflow at top == -1.
  2. Queue rule: FIFO—first in, first out. Array implementation uses front and rear; enqueue increments rear, dequeue increments front. Empty when front > rear.
  3. Parentheses trace: push every opener, pop on a matching closer, and reject immediately if the popped opener does not match. For ({[]}) the stack ends empty → balanced.
  4. Call stack: each function call pushes an activation record with locals and return address; returns pop it. A Python traceback prints this stack with the most recent call last.
  5. Assignment traces: push(5), push(10), pop(), push(15) leaves top = 15 with stack [5,15]; enqueue(A), enqueue(B), dequeue(), enqueue(C) leaves front = B with queue [B,C].

1. Stack — LIFO and Array Implementation

Stack: a linear structure in which insertion and deletion happen at one end called the top. It follows LIFO (Last In, First Out). Operations: push(x) inserts, pop() removes and returns the top, peek() reads the top without removing it.

#include <stdio.h>
#define MAX 5
int s[MAX], top = -1;

void push(int x) {
    if (top == MAX-1) { printf("Stack overflow\n"); return; }
    s[++top] = x;                 /* increment first, then write */
}
int pop(void) {
    if (top == -1) { printf("Stack underflow\n"); return -1; }
    return s[top--];              /* read first, then decrement */
}
int peek(void) {
    if (top == -1) return -1;
    return s[top];                /* no change to top */
}
stack = []
stack.append(5)      # push
stack.append(10)
x = stack.pop()      # returns 10
print(stack[-1])     # peek -> 5
State after operation top Stack contents (bottom → top)
Initial −1 empty
push(5) 0 [5]
push(10) 1 [5,10]
pop() → 10 0 [5]
push(15) 1 [5,15]

All three operations are O(1) because they touch only the top end. This is the reason stacks are used for undo (Ctrl+Z): the most recent action is the first one reversed.

%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
    A[push x] --> B{top == MAX-1?}
    B -->|yes| C[Overflow: cannot push]
    B -->|no| D["top++ ; s[top] = x"]
    E[pop] --> F{top == -1?}
    F -->|yes| G[Underflow: empty]
    F -->|no| H["x = s[top] ; top--"]

Examiner Tip: In a stack-array question, always state the initial value top = -1. If a solution starts at 0 without explaining that index 0 is reserved, the marker may deduct the initialisation mark.


2. Application: Balanced Parentheses Check

Balanced parentheses: every opening bracket has a matching closing bracket of the same type, and nesting is proper. The stack algorithm pushes each opener and pops when a closer is seen; the string is balanced if the stack is empty at the end and no mismatch occurred.

def balanced(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    st = []
    for ch in s:
        if ch in '([{':
            st.append(ch)
        elif ch in ')]}':
            if not st or st.pop() != pairs[ch]:
                return False
    return len(st) == 0

Trace for ({[]}):

Char Action Stack after
( push (
{ push ( {
[ push ( { [
] pop [ matches ( {
} pop { matches (
) pop ( matches empty → balanced

Counter-example ([)]: after ( and [, the ) tries to pop [ — mismatch → not balanced, even though counts of brackets are equal. Counting alone is insufficient; nesting order matters.

Function call stack (concept): calling f() from main() pushes an activation record for f containing parameters, local variables and the return address. When f returns, its record is popped and control resumes in main. Recursive calls push successive records; a Python error traceback is a printed view of this stack, with the latest call at the bottom of the listing.


3. Queue — FIFO and Array Implementation

Queue: a linear structure where insertion occurs at the rear and deletion at the front. It follows FIFO (First In, First Out). Operations: enqueue(x) inserts at rear, dequeue() removes from front.

#include <stdio.h>
#define MAX 5
int q[MAX], front = -1, rear = -1;

void enqueue(int x) {
    if (rear == MAX-1) { printf("Queue overflow\n"); return; }
    if (front == -1) front = 0;
    q[++rear] = x;
}
int dequeue(void) {
    if (front == -1 || front > rear) { printf("Queue underflow\n"); return -1; }
    return q[front++];
}
from collections import deque
q = deque()
q.append('A')       # enqueue
q.append('B')
x = q.popleft()     # dequeue -> 'A'
q.append('C')
print(list(q))      # ['B', 'C'] ; front is B
State front rear Queue contents
Initial −1 −1 empty
enqueue(A) 0 0 [A]
enqueue(B) 0 1 [A,B]
dequeue() → A 1 1 [B]
enqueue(C) 1 2 [B,C]

Linear vs circular queue: in the linear array version above, a dequeue leaves unused cells before front and eventually reports overflow even though those cells are free. A circular queue wraps rear to index 0 using (rear+1) % MAX, reusing freed space. The concept is enough for this unit; the circular linked list of Unit 2 is the pointer-based cousin.

Applications: a print spooler queues documents so the first submitted prints first; task scheduling queues processes so the earliest arrived is served first (FIFO scheduling); WhatsApp messages are delivered in the order queued.

Examiner Tip: For queue code, write both conditions front == -1 and front > rear in the empty test. A single condition fails after all elements have been removed, which examiners test in a trace.


4. Polish Notation

Polish notation (prefix) places the operator before its operands: + A B means A + B. The related reverse Polish notation (postfix) places the operator after operands: A B +. Stacks evaluate postfix expressions by pushing operands and applying an operator to the top two.

Postfix evaluation of 5 3 + 2 *:

Token Action Stack
5 push [5]
3 push [5,3]
+ pop 3, pop 5, push 8 [8]
2 push [8,2]
* pop 2, pop 8, push 16 [16]

Result 16, equal to (5+3)*2. Prefix + 5 * 3 2 evaluates the same expression by scanning right-to-left with a stack. Compilers and calculators use this notation because precedence is explicit and no parentheses are needed.


5. Real Connect Summary

Syllabus phrase Meaning
Ctrl+Z = Stack Undo reverses the most recent action first
WhatsApp delivery = Queue Messages are delivered in send order
Python error traceback IS a call stack Each nested call appears as a frame; the error is at the top of the active stack
CPU scheduling = queue Ready processes wait FIFO in the run queue
Application: print spooler Print jobs wait FIFO until the printer is free

6. Predicted Exam-Ready Questions (Solved — Not Verbatim PYQs)

Predicted Q1 (2 Marks | Peek)

Q (predicted from “peek”): What does the peek operation of a stack do?

Solution: peek() returns the value at the current top without removing it and without changing top. For stack [5,10] with top=1, peek() returns 10 and the stack stays [5,10].


Predicted Q2 (7 Marks | Stack Array Program)

Q (predicted from “implementation using array in C/Python”): Implement push, pop and peek for a stack of size 5 using an array in C. Show the stack after push(5), push(10), pop(), push(15) and state the final top.

Solution: Use the C code from Section 1. Trace:

Operation top Stack
push(5) 0 [5]
push(10) 1 [5,10]
pop() → 10 0 [5]
push(15) 1 [5,15]

Final: top = 1, peek() = 15.


Predicted Q3 (7 Marks | Balanced Parentheses)

Q (predicted from assignment “Check '({[]})' balanced — show stack trace”): Using a stack, check whether ({[]}) is balanced. Show every push and pop.

Solution: Trace from Section 2: push (, push {, push [, pop [, pop {, pop ( → stack empty, no mismatch → balanced. If the input were ([)], the ) would try to pop [, giving a mismatch → not balanced.


Predicted Q4 (7 Marks | Queue Trace)

Q (predicted from assignment “Trace enqueue(A,B), dequeue(), enqueue(C) — what is front?”): Perform enqueue(A), enqueue(B), dequeue(), enqueue(C) on an initially empty queue and state front, rear and contents.

Solution: From Section 3 table: after enqueue(A) front=0,rear=0; after enqueue(B) front=0,rear=1; after dequeue() returns A, front=1,rear=1; after enqueue(C) front=1,rear=2. Contents [B,C], front = B.


Predicted Q5 (7 Marks | Print Spooler / Task Scheduling)

Q (predicted from “Application: print spooler” and “task scheduling queue”): Explain how a queue manages three print jobs J1, J2, J3 and why a stack would be wrong for this application.

Solution: Jobs are enqueued in arrival order: [J1,J2,J3] with front J1. The printer dequeues J1 first, then J2, then J3—FIFO ensures fairness. A stack would print J3 first (LIFO), starving earlier jobs. The same rule applies to a CPU ready queue: the first arrived process is scheduled first under FIFO scheduling.


Predicted Q6 (5 Marks | Function Call Stack)

Q (predicted from “function call stack (concept)”): Describe the role of a stack during recursive function calls.

Solution: Each call pushes an activation record containing parameters, local variables and the return address. For fact(3), records for fact(3), fact(2), fact(1) are pushed in that order; as each returns, its record is popped and control resumes in the caller. Without popping on return, memory would grow without bound; a Python traceback displays these active frames, which is why the error trace looks like a stack.


Predicted Q7 (5 Marks | Polish/Postfix)

Q (predicted from “Polish Notation”): Evaluate the postfix expression 6 2 + 3 * using a stack.

Solution: push 6 → [6]; push 2 → [6,2]; + pops 2 and 6, pushes 8 → [8]; push 3 → [8,3]; * pops 3 and 8, pushes 24 → [24]. Answer: 24, equal to (6+2)*3.


7. Practice Questions (Self-Test)

  1. (2 Marks) What is the condition for stack overflow when MAX = 5 and top starts at −1? (Ans: top == 4.)
  2. (7 Marks) Write a Python function is_balanced(s) and test it on (), ([)], {[]}.
  3. (7 Marks) Implement a circular queue with front = 0, rear = 0 and wrap-around using % MAX; show insertion of 3 elements into a size-4 queue.
  4. (5 Marks) Compare stack and queue with one real application each.
  5. (7 Marks) Evaluate postfix 2 3 * 4 + 5 1 - / with a stack and give the final value.