Unit 3 Stack
Unit 3 Stack
Syllabus:
………………………………………………………………………………………………………………………………………….
INTRODUCTION TO STACK:
What is a Stack?
Stack is a linear data structure in which the insertion and deletion operations are performed at only one end.
In a stack, adding and removing of elements are performed at a single position which is known as "top". That
means, a new element is added at top of the stack and an element is removed from the top of the stack.
In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out)
principle.
A stack data structure can be defined as follows...
Stack is a linear data structure in which the operations are performed based on LIFO principle.
Stack can also be defined as
"A Collection of similar data items in which both insertion and deletion operations are performed based
on LIFO principle".
In a stack, the insertion operation is performed using a function called "push" and deletion operation is
performed using a function called "pop".
In the figure, PUSH and POP operations are performed at a top position in the stack. That means, both the
insertion and deletion operations are performed at one end (i.e., at Top)
When a stack is completely full, it is said to be Stack is Overflow and if stack is completely empty, it is said to be
Stack is Underflow
1
PROPERTIES OF STACK:
There are following important properties of stack-
(i) All insertions and deletions can occur only at the top of stack.
(ii) The elements that are removed from stack in reverse order in which they were inserted.
(iii) Only one element can be pushed or popped from the stack at a time.
2
OPERATIONS ON STACKS:
3
Algorithm for PEEK operation
Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.
Before pushing the element to the stack, we check if the stack is full .
4
If the stack is full (top == capacity-1) , then Stack Overflows and we cannot insert the element to the stack.
Otherwise, we increment the value of top by 1 (top = top + 1) and the new value is inserted at top position .
The elements can be pushed into the stack till we reach the capacity of the stack.
5
Pop Operation in Stack:
Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the
stack is empty, then it is said to be an Underflow condition.
Before popping the element from the stack, we check if the stack is empty .
If the stack is empty (top == -1), then Stack Underflows and we cannot remove any element from the stack.
Otherwise, we store the value at top, decrement the value of top by 1 (top = top – 1) and return the stored top
value.
6
7
Top or Peek Operation in Stack:
Before returning the top element from the stack, we check if the stack is empty.
In a linked stack, each node of the stack consists of two parts i.e. data part and the next part.
Each element of the stack points to its immediate next element in the memory.
In the linked stack, there one pointer maintained in the
memory i.e. TOP pointer. The TOP pointer contains the
address of the starting element of the STACK.
Both Insertion and deletions are performed at only one end
called TOP. If TOP is NULL, it indicates that the stack is empty. Initially
PUSH function: PUSH function will add the element at the beginning of the linked list.
1. Declare a new node and allocate memory for it.
2. If TOP == NULL, make TOP points to the new node.
3. Otherwise, add the new node at TOP end and makes the next of new node is previous TOP.
9
POP function: POP function will remove the TOP element from the STACK.
We can use the following steps to delete a node from the stack...
Algorithms:
Or
void pop() {
if(top == NULL)
printf("\nStack is Empty!\n");
else {
top = temp->next;
free(temp);
10
Logic :
if (newNode == NULL) {
return;
newNode->data = value;
if(top == NULL)
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion successful!\n");
Applications of stack;
• Expression Evaluation and Conversion (Infix to Postfix/Prefix).
• Function Call Management (Call Stack for Recursion).
• Undo and Redo Operations in text editors and applications.
• Browser Navigation (Back and Forward Buttons).
• Parentheses Matching and Syntax Parsing in compilers.
• Memory Management (Runtime Stack in Memory Allocation).
• Depth-First Search (DFS) in graphs and trees.
• Tower of Hanoi Problem (Recursive Stack Simulation).
• Backtracking Problems (e.g., maze solving, Sudoku).
• Expression Tree Construction for arithmetic expressions.
• Virtual Machine and CPU Operations (Stack-Based Machines).
• Reversing a String using stack operations (push and pop).
• Factorial calculations
11
Applications of Stacks (other examples)
✔ Stack is used to reversing the given string.
✔ Stack is used to evaluate a postfix expression.
Reversing list:
A list of numbers or string can be reversed by using the stack, perform the following steps
1. Reading the elements from the array and pushed into the stack.
2. Pop the elements and again stored into the array starting from first index
Algorithm: Example:
Stack in Backtracking
A stack can be used to implement the backtracking
mechanism efficiently. In this approach, every decision (state) is pushed onto the
stack. If the current path leads to a solution, we continue, but if it doesn't, we pop
from the stack to backtrack and try other options.
Steps in Backtracking with Stack:
1. Push the current state/decision onto the stack.
2. Check if the current state is valid.
1. If yes, explore the next step.
2. If no, pop the state and backtrack.
3.Repeat until a solution is found or all possibilities are exhausted
Real time example
1. Solving a Maze or Navigating a Map (GPS-based Pathfinding)
Scenario: Imagine you're navigating through a complex city using GPS, and you
encounter several dead-end streets. A GPS algorithm must backtrack when it
12
reaches a blocked road to explore alternate paths.
Backtracking with Stack:
• Each intersection (decision point) is pushed onto the stack.
• If a path leads to a dead end, it pops the last decision and tries other routes.
• Eventually, it finds the shortest path or exits when all possibilities are
explored.
Real-Time Backtracking with Stack Applications
Evaluation of Expressions:-
What is an Expression?
In any programming language, if we want to perform any calculation or to frame a condition etc., we use a set of
In above definition, operator is a symbol which performs a particular task like arithmetic operation or logical operation
Operands are the values on which the operators can perform the task. Here operand can be a direct value or variable
Expression Types
Based on the operator position, expressions are divided into THREE types. They are as follows...
1. Infix Expression
2. Postfix Expression
13
3. Prefix Expression
Infix Expression
Example
Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the Operands".
Example
Prefix Expression
In prefix expression, operator is used before operands. We can say that "Operands follows the Operator".
Example
Every expression can be represented using all the above three different types of expressions. And we can convert an
expression from one form to another form like Infix to Postfix, Infix to Prefix, Prefix to Postfix and vice versa.
14
Operator Precedence: When an expression consist different level of operators we follow it. We
consider five binary operations: +, -, *, / and ^ (exponentiation). For these binary operations, the
following in the order of precedence (highest to lowest): ^ , * , /, +, -
Operator Associativity: When an expression consist more than one same level precedence operators
we follow it.
Basically we have Left to Right associativity and Right to Left Associativity. Most of the operators
are follows Left to Right but some of the operators are follow Right to left Associativity like Unary
(+/-), ++/-- , Logical negation (!), Pointer and address (*,&), Conditional Operators and Assignment
operators(=,+=,-=,*=,/=,%=).
Example: x=a/b–c+d*e–a*c
= ((4 / 2) – 2) + (3 * 3) – (4 * 2) =0+9–8 =1
one type of expression to another type of expression like Infix to Postfix, Infix to Prefix, Postfix to Prefix and vice
versa.
To convert any Infix expression into Postfix or Prefix expression we can use the following procedure...
3. Convert each operator into required type of expression (Postfix or Prefix) in the same order.
Example
D=A+B*C
15
DABC*+=
(A+B)*(C-D)
The given infix expression can be converted into postfix expression using Stack data Structure
16
follows...
The final Postfix Expression is as follows...
17
AB+CD-*
EXAMPLE:2
18
Example:3
19
EVALUATION OF POSTFIX EXPRESSION:
A postfix expression is a collection of operators and operands in which the operator is placed after the operands. That
Example
A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix expression using Stack
1. Read all the symbols one by one from left to right in the given Postfix Expression
3. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and store the two
popped oparands in two different variables (operand1 and operand2). Then perform reading symbol
operation using operand1 and operand2 and push result back on to the Stack.
4. Finally! perform a pop operation and display the popped value as final result.
Example
20
21
Final Result is 48
Example:02
Example:03
22
Conversion of Infix to Prefix using Stack
Simple Steps:
1. Reverse the given infix expression.
2. Swap the parentheses (i.e., replace ( with ) and ) with ().
3. Convert the modified reversed expression to postfix.
4. Reverse the postfix expression to get the final prefix expression.
Given Infix - ((a/b)+c)-(d+(e*f))
Step 1: Reverse the infix string. Note that while reversing the string you must interchange left and right parentheses.
Step 2: Obtain the postfix expression of the expression obtained from Step 1.
Step 3: Reverse the postfix expression to get the prefix expression
23
Sr. No. Expression Stack Prefix
0 ( (
1 ( ((
2 f (( f
3 * ((* f
4 e ((* fe
5 ) ( fe*
6 + (+ fe*
7 d (+ fe*d
8 ) fe*d+
9 – – fe*d+
10 ( -( fe*d+
11 c -( fe*d+c
12 + -(+ fe*d+c
13 ( -(+( fe*d+c
14 b -(+( fe*d+cb
15 / -(+(/ fe*d+cb
16 a -(+(/ fe*d+cba
17 ) -(+ fe*d+cba/
18 ) – fe*d+cba/+
19 fe*d+cba/+-
Final prefix: -+/abc+d*ef
24