Stack Unit 2
Stack Unit 2
Unit 2: Stacks
Abstract data type • Push & Pop • Array & Linked-List
Implementations of Stack • Expressions • Recursion
TOP
LIFO 40
20
10
40 leaves first
Learning outcomes
• Implement push, pop, peek, isEmpty and isFull using arrays and linked nodes in C.
• Use stacks to understand infix, prefix and postfix notation and evaluate postfix expressions.
• Explain recursion using base case, recursive case and the call stack.
• Solve problems with recursive and iterative binary search, Fibonacci and Tower of Hanoi.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
ROADMAP 3
Expressions Evaluation
03 04
Infix, prefix, postfix and conversion Step-by-step postfix evaluation
Trade-offs
07
When iteration or recursion is preferable
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
FUNDAMENTALS 4
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
FUNDAMENTALS 5
10 20 30 20
10
10 20 10
10
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PRIMITIVE OPERATIONS 6
PUSH(x) POP()
30
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RUNNING EXAMPLE 7
10 20 30 20 40
10 20 10 20
→ → → 10 → → 10
Key idea: every operation changes only the TOP; arbitrary middle access is not a stack operation.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
IMPLEMENTATION 8
Array-based stack in C
// C IMPLEMENTATION
#include <stdio.h> How TOP works
#define MAX 100
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
IMPLEMENTATION 9
//HELPER FUNCTIONS
• Overflow push is attempted when top == MAX - 1.
int peek(Stack *s) {
if (s->top == -1) return -1;
return s->data[s->top]; • Underflow pop or peek is attempted when top ==
-1.
}
• Complexity push, pop and peek are O(1).
int isEmpty(Stack *s) {
return s->top == -1;
}
• Memory O(MAX) reserved, even if only a few items
are used.
int isFull(Stack *s) {
return s->top == MAX - 1;
}
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
IMPLEMENTATION 10
Linked-List stack in C
// POINTER-BASED IMPLEMENTATION
#include <stdlib.h>
Top node changes
typedef struct Node {
int data;
struct Node *next;
} Node; 20
30
typedef struct {
Node *top;
} Stack;
Push inserts at the front; pop removes the front. Both are O(1).
10 NULL 30 10 10 20
20 10 10 NULL 20 NULL
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
IMPLEMENTATION 12
Both provide the same stack ADT; only the storage strategy changes.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
APPLICATION 13
(A + B) * C *+ABC AB+C*
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
APPLICATION 14
The stack temporarily holds operators while operands go directly to the output.
High ^ Right-to-left
• ( push onto operator stack.
Medium * / Left-to-right
• ) pop until ( is removed.
Low + - Left-to-right
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RUNNING EXAMPLE 15
( (
A A (
+ A (+
B AB (+
) AB+
* AB+ *
C AB+C *
end AB+C*
Final postfix: AB+C* Important cue: ask yourself why + waits behind (
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
APPLICATION 16
Example: 5 6 2 + *
5 push 5 [5]
6 push 6 [5, 6]
2 push 2 [5, 6, 2]
Result = 40
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
IMPLEMENTATION 17
Postfix evaluation in C
// SINGLE-DIGIT OPERANDS
• Important-→ this compact example
int evaluatePostfix(const char *exp) { accepts single-digit operands.
Stack s; init(&s);
for (int i = 0; exp[i] != '\0'; i++) { • For 25 3 + tokenize the expression instead
if (isdigit((unsigned char)exp[i])) { of reading one character at a time.
push(&s, exp[i] - '0');
} else {
int b = pop(&s); • Operator order for subtraction/division, first
int a = pop(&s); pop is b and second pop is a; compute a op b.
switch (exp[i]) {
case '+': push(&s, a + b); break;
case '-': push(&s, a - b); break; Complexity O(n) time and O(n) auxiliary
•
case '*': push(&s, a * b); break; stack space.
case '/': push(&s, a / b); break;
}
}
}
return pop(&s);
}
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
APPLICATION 18
4 push
• Evaluation scan right-to-left; operand → push;
operator → pop two, compute, push.
3 push
• Postfix scan left-to-right with the same stack
pattern.
2 push
* 5×4=20
Both notations are useful applications of the stack ADT.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RECURSION 19
Principles of recursion
• Call stack each active call gets its own stack frame. return n * fact(n - 1);
}
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RECURSION 20
TOP
Unwinding
1
fact(4) 4 × 6 = 24
fact(3) 3×2=6
fact(2) 2×1=2
24
fact(1) return 1
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RECURSION 21
Tail recursion
• Definition the recursive call is the final operation of //TAIL CALL //Rec. CALL
the function. long long factTail (int n, long long acc)
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RECURSION 22
Removing recursion
2 Explicit stack Store pending states yourself when recursion has hidden state.
Note: memorization improves a recursive algorithm; it does not by itself remove recursion.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PROBLEM SOLVING 23
//RECURSIVE IMPLEMENTATION IN C
Search 70
int binarySearchRec(int a[], int low, int high, int key)
{
if (low > high) return -1; 10 20 30
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PROBLEM SOLVING 24
//ITERATIVE IMPLEMENTATION IN C
• Same search time O(log n).
int binarySearchIter(int a[], int n, int key)
{
int low = 0, high = n – 1; • Less auxiliary memory O(1) instead of O(log n)
call-stack space.
while (low <= high) • Practical choice often preferred for simple binary
{ search in C.
int mid = low + (high - low) / 2;
if (a[mid] == key) return mid; low ≤ high → inspect mid → discard half
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
COMPARISON 25
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PROBLEM SOLVING 26
// FIB. IN RECURSIVE C
Repeated work in fib(5)
int fibRec(int n)
fib(5)
{
if (n <= 1) return n;
fib(4) fib(3)
return fibRec(n - 1) + fibRec(n - 2);
}
fib(3) fib(2) fib(2) fib(1)
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PROBLEM SOLVING 27
//FIB. ITERATIVE C
Two better choices
int fibIter(int n)
Iteration O(n) time • O(1) space
{
if (n <= 1) return n;
int a = 0, b = 1; Memorization O(n) time • O(n) space
for (int i = 2; i <= n; i++) {
int c = a + b;
a = b; b = c; Memorization keeps recursive structure while
} caching fib(k).
return b;
}
0 1 1 2 3 5 8 13 …
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PROBLEM SOLVING 28
Tower of Hanoi
Rules
A B C
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
PROBLEM SOLVING 29
//RECURSIVE ToH IN C
For n = 3
void hanoi(int n, char src, char aux, char dest)
{ 1. A → C
if (n == 1) 2. A → B
{
3. C → B
printf("Move disk 1 from %c to %c\n", src, dest);
return; 4. A → C
}
5. B → A
hanoi(n - 1, src, dest, aux);
6. B → C
printf("Move disk %d from %c to %c\n", n, src, dest);
7. A → C
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
TRADE-OFFS 30
Iteration vs recursion
Clarity Often concise for recursive structures Often straightforward for loops
Auxiliary memory Call-stack frames may grow Usually constant extra state
Call overhead Present for each recursive call No recursive call overhead
Overflow risk Deep recursion can overflow the call stack No recursion-depth risk
Natural fit Trees, divide-and-conquer, backtracking Simple scans, counters, performance-critical loops
Best question Is the problem naturally recursive? Can a loop express it more simply?
Neither is universally better: choose based on structure, memory, depth and clarity.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
DECISION GUIDE 31
✓ the problem naturally breaks into smaller copies of ✓ a loop expresses the same logic clearly
itself
✓ backtracking / tree traversal is the natural model ✓ performance and predictable memory matter
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
RECAP 32
Key takeaways
• Stack ADT LIFO with push, pop, peek and state-check operations.
• Postfix evaluation scan left-to-right; operands push; operators pop two, compute, push.
• Recursion needs a base case, progress toward it and uses the call stack.
• Examples Binary search: O(log n); Fibonacci: iteration/memorization improve naive recursion; Hanoi: naturally recursive, 2ⁿ−1
moves.
• Trade-off recursion can improve structure; iteration usually reduces call-stack memory.
Remember: the right control structure is the one that makes correctness, cost and intent clear.
Ananjay Kumar Singh • Dept. of Data Science • Galgotias College of Engineering and Technology DATA STRUCTURE • BCS301 • Unit 2: Stacks
THANK YOU
STACK EXPR.
LIFO Postfix
RECURSION TRADE-OFFS