Chapter 3 Stacks
Chapter 3 Stacks
R
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
Contents
LICENSE 3
CHAPTER 3: STACKS 4
CHAPTER NOTES.............................................................................................................................4
3.1 Introduction..........................................................................................................................4
3.2 Stack.....................................................................................................................................4
3.2.1 Applications of Stack........................................................................................................4
3.3 Operations on Stack.............................................................................................................5
3.4 Implementation of Stack in Python......................................................................................5
3.5 Notations for Arithmetic Expressions..................................................................................7
3.6 Conversion from Infix to Postfix.........................................................................................7
3.7 Evaluation of Postfix Expression.........................................................................................8
Summary Points.........................................................................................................................8
2 MARKS QUESTIONS 17
3 MARKS QUESTIONS 18
5 MARKS QUETIONS 21
2
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
CHAPTER 3: STACKS
CHAPTER NOTES
3.1 Introduction
3.2 Stack
• Definition: A linear data structure where elements are added/removed from one end (TOP).
• LIFO Principle: Last In, First Out – the last element added is the first to be removed.
• Analogy: Stack of plates or books – add/remove only from the top.
3.2.1Applications of Stack
Real-life Scenarios
1. Pile of clothes in an almirah – Clothes are added or removed from the top of the pile,
following the LIFO order.
2. Multiple chairs in a vertical pile – Chairs are stacked one on top of the other, and removed in
reverse order.
3. Bangles worn on the wrist – The last bangle worn is the first to be removed.
4. Boxes of eatables in pantry – Boxes are added and removed from the top for convenience.
Programming Applications
1. String Reversal
• Characters are added to a stack and popped in reverse order to reverse the string.
2. Undo/Redo in Editors
• Each edit (text/image) is pushed onto a stack. Undo removes the last change, redo re-
applies it.
3
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
• Navigated pages are pushed onto a stack. Pressing ‘Back’ pops the last visited page and
returns to the previous one.
• During program execution, a stack is used to ensure every opening parenthesis has a
matching closing one. It helps identify syntax errors like unmatched or misnested
parentheses.
Functions:
# Create an empty stack
glassStack = list()
# PUSH operation
def opPush(glassStack, element):
glassStack.append(element)
# POP operation
def opPop(glassStack):
if isEmpty(glassStack):
print("underflow")
return None
else:
4
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
return glassStack.pop()
Sample Program:
glassStack = list() # create empty stack
element = 'glass1'
print("Pushing element", element)
opPush(glassStack, element)
element = 'glass2'
print("Pushing element", element)
opPush(glassStack, element)
element = opPop(glassStack)
print("Popped element is", element)
element = 'glass3'
print("Pushing element", element)
opPush(glassStack, element)
5
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
Why? Computers struggle with operator precedence in infix; postfix avoids this.
• If ( → PUSH to stack
• If ) → POP and add to postExp until ( is found
• If operator:
– POP higher or equal precedence operators and append to postExp
6
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
Algorithm 3.2:
1. For each character in postfix expression:
Example: 7 8 2 * 4 / + → Result: 11
Summary Points
7
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
C. LIFO
D. FILO
Answer: C. LIFO
5. Which method in Python list is used to remove the top element in a stack?
A. remove()
B. del()
C. pop()
D. discard()
Answer: C. pop()
8
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
9. What type of error occurs when trying to push an element into a full stack (in languages with
fixed stack size)?
A. Syntax Error
B. Runtime Error
C. Overflow
D. Underflow
Answer: C. Overflow
9
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
12. In the conversion of infix to postfix, where are the operators stored during processing?
A. Queue
B. List
C. Stack
D. Array
Answer: C. Stack
13. Which function is used to read the topmost element from the stack?
A. pop()
B. top()
C. peek()
D. get()
Answer: B. top()
14. What is the output of the top() function when the stack is empty?
A. 0
10
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
B. Error
C. None
D. Null
Answer: C. None
15. What is the postfix equivalent of the infix expression (x + y)/(z * 8)?
A. xy+z8/
B. +xyz8/
C. /+xyz8
D. x+yz/8
**Answer: A. xy+z8*/**
18. During infix to postfix conversion, what happens when a right parenthesis is encountered?
A. It is ignored
B. It is pushed to stack
C. Operators are popped till left parenthesis
D. Nothing happens
Answer: C. Operators are popped till left parenthesis
11
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
19. Which one of the following statements is FALSE about stack operations in Python (based on
the chapter)?
A. append() is used to push elements
B. pop() removes the topmost element
C. We declare stack size in Python
D. Stack can be implemented using list
Answer: C. We declare stack size in Python
22.
Assertion (A): The pop() method in Python list implementation of a stack removes the first element.
Reason (R): In stack implementation, elements are always inserted and removed from the beginning of
the list.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: D
12
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
23.
Assertion (A): Stack is a useful data structure for reversing a string.
Reason (R): Stack allows deletion of elements from the bottom, enabling reverse traversal.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: C
24.
Assertion (A): A stack is used for matching parentheses in expressions.
Reason (R): Stack helps in storing and retrieving nested structures in reverse order.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: A
25.
Assertion (A): Overflow condition occurs when an element is inserted into a full stack in Python.
Reason (R): Python lists have a fixed size and cannot grow beyond a limit.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: C
26.
Assertion (A): Infix expressions are easy for humans to read but difficult for machines to evaluate.
Reason (R): Infix expressions require knowledge of operator precedence and parentheses handling.
13
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
27.
Assertion (A): In postfix notation, parentheses are not required.
Reason (R): Postfix notation places operators in a way that respects operator precedence inherently.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: A
28.
Assertion (A): While converting an infix expression to postfix, operands are pushed onto the stack.
Reason (R): The stack is used to hold operands and not operators.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: C
29.
Assertion (A): In evaluation of postfix expression, operators are pushed onto the stack.
Reason (R): Stack helps evaluate binary operators from left to right.
A. Both A and R are true, and R is the correct explanation of A
B. Both A and R are true, but R is not the correct explanation of A
C. A is true, but R is false
D. A is false, but R is true
Answer: D
14
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
30.
Assertion (A): Stack is a helpful structure in browser history navigation.
Reason (R): The back button uses LIFO mechanism to navigate to the previous pages.
1. A is a linear data structure in which insertion and deletion are done from the same end.
Answer: Stack
2. Stack follows the principle, where the last element added is the first one removed.
Answer: LIFO (Last-In-First-Out)
7. In stack implementation using Python list, elements are added using the method.
Answer: append()
9. The function retrieves the most recently added element without removing it.
Answer: top
15
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
13. During infix to postfix conversion, only are pushed onto the stack.
Answer: operators
14. In evaluation of postfix expression, only are pushed onto the stack.
Answer: operands
2 MARKS QUESTIONS
glassStack = []
glassStack.append('glass1')
16
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
def isEmpty(glassStack):
if len(glassStack) == 0:
return True
else:
return False
3 MARKS QUESTIONS
17
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
1. Reversing a String: By pushing all characters onto a stack and then popping them, the string is
reversed.
2. Undo/Redo Operations: In text/image editors, changes are pushed onto a stack. Undo pops the
last action, and redo re-applies it.
3. Parentheses Matching: Compilers use stacks to ensure that every opening parenthesis has a
match- ing closing one and is properly nested.
2. Q: Differentiate between Infix, Prefix, and Postfix notation. Provide one example for
each. A:
| Type | Description | Example | |———|————————————–|——————–| | Infix |
Opera- tor between operands | (x + y) / (z * 5)| | Prefix | Operator before operands (Polish) |
/+xy*z5 | | Postfix | Operator after operands (Reverse Polish) | xy+z5*/ |
3. Q: Write a Python function to display the elements of a stack from top to bottom. Also,
explain what it does.
A:
def display(glassStack):
x = len(glassStack)
print("Current elements in the stack are: ")
for i in range(x-1, -1, -1):
print(glassStack[i])
Explanation:
The display() function prints the contents of the stack glassStack from the top element to the bot-
tom, using reverse indexing.
4. Q: Explain the steps involved in converting an infix expression to a postfix expression using
stack.
A:
Steps for conversion: 1. Traverse each character in the infix expression. 2. If it’s an operand, append it
to the postfix string. 3. If it’s a left parenthesis (, push to the stack. 4. If it’s a right parenthesis ), pop
and append operators until a matching ( is found. 5. If it’s an operator, pop higher precedence
operators from the stack and append to postfix, then push the current operator. 6. After processing all
characters, pop remaining stack contents to postfix expression.
5. Q: What is the role of a stack in evaluating a postfix expression? Explain the process with
steps. A:
To evaluate a postfix expression using stack: 1. Read the postfix expression left to right. 2. If an
operand is encountered, push it onto the stack. 3. If an operator is encountered, pop two elements,
apply the operator, and push the result back. 4. After processing, the final result will be the only value
remaining in the stack.
18
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
6. Q: What will be the output of the following code segment? Explain each step.
answer=[]; output=''
answer.append('T')
answer.append('A')
answer.append('M')
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
print("Result=",output)
A:
Output: Result=MAT
Explanation: - Stack: T → A → M
- POP 1: ‘M’ → output = “M”
- POP 2: ‘A’ → output = “MA”
- POP 3: ‘T’ → output = “MAT”
7. Q: Write Python functions opPush() and opPop() used in stack operations. Explain how
they work.
A:
def opPop(glassStack):
if isEmpty(glassStack):
print("underflow")
return None
else:
return glassStack.pop()
Explanation:
- opPush() uses append() to add elements to the TOP of the stack.
- opPop() checks if the stack is empty before using pop() to remove the top element.
8. Q: Differentiate between overflow and underflow in stack operations. How does Python
handle these conditions?
A:
- Overflow: Occurs when trying to PUSH into a full stack. In Python, this is rare because lists are
dynamic.
20
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
- Underflow: Occurs when trying to POP from an empty stack. Python raises an error or custom
message when this is handled. - Python handles underflow using conditional checks (isEmpty()), and
overflow is not typical due to dynamic memory allocation.
5 MARKS QUETIONS
2. Q: Explain the PUSH and POP operations in a stack. Give Python functions for
both. A:
- PUSH: Adds an element to the top of the stack.
- POP: Removes the topmost element from the
stack. Python implementation:
def opPop(glassStack):
if isEmpty(glassStack):
print("underflow")
return None
else:
return glassStack.pop()
These functions use append() to push and pop() to pop elements from a Python list used as a stack.
3. Q: Differentiate between Infix, Prefix, and Postfix notations. Give one example of
each. A:
| Type | Description | Example | |———|————————————–|——————–| | Infix | Opera-
tor between operands | (x + y) / (z * 5)| | Prefix | Operator before operands (Polish) | /+xy*z5 | |
Postfix | Operator after operands (Reverse Polish) | xy+z5*/ |
21
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
glassStack = list()
opPush(glassStack, 'glass1')
opPush(glassStack, 'glass2')
print("Top element is:", top(glassStack))
element = opPop(glassStack)
print("Popped element is:", element)
opPush(glassStack, 'glass3')
display(glassStack)
This demonstrates pushing, popping, and reading the topmost element using stack operations.
6. Q: What are overflow and underflow in the context of stacks? How are these handled in
Python? A:
- Overflow: Occurs when trying to push into a full stack (not typical in Python).
- Underflow: Occurs when trying to pop from an empty
stack. Python handles underflow using checks like:
if isEmpty(stack): print("underflow")
22
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
to postExp until ( is found. 6. If operator → pop higher precedence operators to postExp, then push
current. 7. After traversal, pop remaining stack contents to postExp.
8. Q: Convert the infix expression (x + y)/(z * 8) into postfix using stack and show steps.
A:
Given infix: (x + y)/(z * 8)
Steps: - Push (
- Append x, then y
- Operator + pushed, then popped after ) → xy+
- Operator / pushed
- Push (, then z, 8
- Operator * pushed, then popped after ) → z8*
- / popped → Final: xy+z8*/
9. Q: Describe the algorithm for evaluating a postfix expression using
stack. A:
Algorithm: 1. Read the postfix expression left to right. 2. If operand → push to stack. 3. If operator →
pop two elements, apply operator, push result. 4. Final element in stack = result.
10. Q: Evaluate the postfix expression 7 8 2 * 4 / + using stack and show stack state after each
step.
A:
Expression: 7 8 2 * 4 / +
Steps: - Push 7 → [7]
- Push 8 → [7, 8]
- Push 2 → [7, 8, 2]
- * → 8 * 2 = 16 → [7, 16]
- Push 4 → [7, 16, 4]
- / → 16 / 4 = 4 → [7, 4]
- + → 7 + 4 = 11 → [11]
Result: 11
11. Q: Write the Python function top() to retrieve the topmost element in a stack with empty
check.
A:
def top(glassStack):
if isEmpty(glassStack):
print("Stack is empty")
return None
else:
return glassStack[-1]
23
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
It returns the last element in the list, which is the top of the stack.
12. Q: Explain the display() function used to print stack contents in Python. Provide code and
output format.
A:
def display(glassStack):
x = len(glassStack)
print("Current elements in the stack are:")
for i in range(x-1, -1, -1):
print(glassStack[i])
def reverseString(s):
stack = []
for char in s:
stack.append(char)
rev = ''
while stack:
rev += stack.pop()
return rev
print(reverseString("STACK"))
Output: KCATS
14. Q: Convert the infix expression A + B - C * D to postfix and show stack/string at each
step. A:
Steps: - Append A → A
- + → push
- Append B → AB
- - → pop + → AB+, push -
- Append C → AB+C
- * → push
- Append D → AB+CD
- Pop * then - → AB+CD*-
24
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
A:
stack = []
nums = [1, 2, 9, 4, 7, 10]
for n in nums:
if n % 2 != 0:
stack.append(n)
maxOdd = float('-inf')
while stack:
ele = stack.pop()
print("Popped:", ele)
if ele > maxOdd:
maxOdd = ele
17. Q: Give a step-by-step evaluation of the postfix expression: A B + C * where A=3, B=5,
C=1. A:
- A = 3, B = 5, C = 1
Expression: 3 5 + 1 *
- 3, 5 → push
- + → 3+5 = 8
- push 1
-*→8*1=8
Result: 8
25
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
CHAPTER END EXERCISES
Answers:
a) True
b) False
c) False
d) True
code: a)
result = 0
numberList = [10, 20, 30]
numberList.append(40)
result = result + numberList.pop()
result = result + numberList.pop()
print("Result =", result)
Output:
Result = 70
Explanation:
- Stack after append: [10, 20, 30, 40]
- POP 1: 40 → result = 0 + 40 = 40
- POP 2: 30 → result = 40 + 30 = 70
b)
26
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
print("Result =", output)
Output:
Result = MAT
Explanation:
- Stack after pushes: [‘T’, ‘A’, ‘M’]
- Popped characters: ‘M’, ‘A’, ‘T’ → added to output in reverse
stack. Answer:
def reverseString(s):
stack = []
for char in s:
stack.append(char)
rev = ''
while stack:
rev += stack.pop()
return rev
print(reverseString("STACK"))
Output:
KCATS
((2 + 3) * (4 / 2)) + 2
Show step-by-step process for matching parentheses using stack.
27
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
Conclusion:
All parentheses matched and stack is empty at end → Parentheses are properly nested and matched.
a) A B + C * → 3 5 + 1 *
Answer:
• 3+5=8
• 8*1=8
b) A B * C / D * → 3 5 * 1 / 4 *
Answer:
• 3 * 5 = 15
• 15 / 1 = 15
• 15 * 4 = 60
6. Convert the following infix notations to postfix notations. Show stack and string contents at
each step.
a) A + B - C * D
Postfix: AB+CD*-
b) A * ((C + D)/E)
Postfix: ACD+E/*
7. Write a program to create a Stack for storing only odd numbers out of all the numbers
entered by the user. Display the content of the Stack along with the largest odd number in the
Stack.
Answer:
28
STUDENT NOTES || CHAPTER 3 April 18, 2025
STACKS
largest = float('-inf')
print("Odd numbers in stack:")
while stack:
item = stack.pop()
print(item)
if item > largest:
largest = item
Sample Output:
29