05/03/2025
JSPM's RSCOE
Unit III: Stacks
Dr. Rushali A. Deshmukh
*CONTENTS
LIFO Principle,
Stack as an ADT,
Representation and Implementation of Stack using Sequential and
Linked Organization.
Applications of Stack- Simulating Recursion using Stack,
Arithmetic Expression Conversion and Evaluation,
Reversing a String.
Time complexity analysis of Stack operations
JSPM's RSCOE
05/03/2025
JSPM's RSCOE
Concept of Stack
❖Stores a set of elements in a particular order
❖Stack principle: LAST IN FIRST OUT (LIFO). It means: The
last element inserted is the first one to be removed
❖Example
❖Which is the first element to pick up?
JSPM's RSCOE
Stack Definition
❖A stack is an ordered collection of homogeneous items into which
new items may be inserted and from which items may be deleted at one
end, called the top of the stack.
❖Linear Data Structure
❖Restricted Data Structure - The deletion and insertion in a stack is
done from top of the stack.
❖LIFO: (Last In, First Out), FILO (First In, Last Out)
STACK
push
create
pop
isfull
isempty
05/03/2025
JSPM's RSCOE
Stack - Primitive operations
❖CreateEmptyStack(S): Create or make stack S be an empty stack
❖Push(S, x): Insert x at one end of the stack, called its top
❖Pop(S): If stack S is not empty; then delete the element at its top
❖Top(S): If stack S is not empty; then retrieve the element at its top
❖ IsFull(S): Determine if S is full or not. Return true if S is full
stack; return false otherwise
❖IsEmpty(S): Determine if S is empty or not. Return true if S is an
empty stack; return false otherwise.
05/03/2025
JSPM's RSCOE
05/03/2025
JSPM's RSCOE
05/03/2025
JSPM's RSCOE
Stack as ADT
objects: a finite ordered list with zero or more elements.
methods:
for all stack Stack, item element, max_stack_size positive
∈ ∈ ∈
integer
Stack createS(max_stack_size) ::=
create an empty stack whose maximum size is
max_stack_size
Boolean isFull(stack, max_stack_size) ::=
if (number of elements in stack == max_stack_size)
return TRUE
else return FALSE
05/03/2025
JSPM's RSCOE
Stack push(stack, item) ::=
if (IsFull(stack)) stack_full
else insert item into top of stack and return
Boolean isEmpty(stack) ::=
if(stack == CreateS(max_stack_size))
return TRUE
else return FALSE
Element pop(stack) ::=
if(IsEmpty(stack)) return
else remove and return the item on the top of the stack.
05/03/2025
JSPM's RSCOE
#include <iostream>
using namespace std;
#define Maxsize 100
class Stack
{
int data[Maxsize];
int top;
public:
void create();
bool isfull();
bool isempty();
void push(int d);
int pop();
int stacktop();
};
Stack Implementation using array in C++
05/03/2025
JSPM's RSCOE
int Stack::stacktop()
{
if(!isempty())
return data[top];
else
return -1;
}
bool Stack::isempty()
{
if(top == -1)
{
cout<<top;
cout<<"stack is empty";
return true;
}
else
return false;
}
05/03/2025
JSPM's RSCOE
bool Stack::isfull()
{
if(top == Maxsize-1)
{
cout<<"stack is full";
return true;
}
else
return false;
}
void Stack::create()
{
top = -1;
}
int Stack::pop()
{
if(!isempty())
return data[top--];
else
return 0;
}
JSPM's RSCOE
void Stack::push(int ele)
{
if(!isfull())
data[++top]=ele;
}
int main() {
// Write C++ code here
Stack s1;
s1.create();
s1.isempty();
s1.push(10);
cout<<s1.stacktop();
s1.push(20);
s1.push(30);
cout<<s1.pop();
cout<<s1.pop();
cout<<s1.pop();
s1.isempty();
return 0;
}
05/03/2025
JSPM's RSCOE
Complexity Analysis for stack implementation using
array:
•:
◦push: O(1)
◦pop: O(1)
◦peek: O(1)
◦is_empty: O(1)
◦is_full: O(1)
•:Space Complexity: O(n), where n is the number of items in
the stack.
05/03/2025
JSPM's RSCOE
Advantages of Array Implementation:
•Easy to implement.
•Memory is saved as pointers are not involved.
Disadvantages of Array Implementation:
•It is not dynamic i.e., it doesn’t grow and shrink
depending on needs at runtime. [But in case of dynamic
sized arrays like vector in C++, list in Python, ArrayList in
Java, stacks can grow and shrink with array]
implementation as well].
•The total size of the stack must be defined beforehand.
Autumn 2016
Autumn 2016
top
PUSH OPERATION
Push using Linked List
Autumn 2016
Autumn 2016
top
POP OPERATION
Pop using Linked List
• In the array implementation, we would:
• Declare an array of fixed size (which determines the maximum
size of the stack).
• Keep a variable which always points to the “top” of the stack.
• Contains the array index of the “top” element.
• In the linked list implementation, we would:
• Maintain the stack as a linked list.
• A pointer variable top points to the start of the list.
• The first element of the linked list is considered as the stack top.
Autumn 2016
Autumn 2016
Basic Idea
05/03/2025
JSPM's RSCOE
Infix, Prefix, & Postfix Notations
Infix Notation
• The operator is between operands
• A problem is that we need parentheses or precedence rules to
handle more complicated expressions:
For Example : a + b * c is (a + b) * c ? OR a + (b *
c) ?
How do you figure out the operands of an operator?
Infix Notation - Operator Priority
• Operators are assigned priorities
priority(*) = priority(/) > priority(+) = priority(-)
• When an operand lies between two operators, the operand
associates with the operator that has higher priority.
05/03/2025
JSPM's RSCOE
Infix, Prefix, & Postfix Notations
Infix Notation - Associativity
•When an operand lies between two operators that have
the same priority, the operand associates with the operator
on the left or on the right
a + b - c
a * b / c / d
05/03/2025
JSPM's RSCOE
Polish Notation (Prefix Notation)
• Introduced by the Polish logician Lukasiewicz
• Operators are placed on the left of their operands.
• If the operator has a defined fixed number of operands,
the syntax does not require brackets or parenthesis to lessen
ambiguity.
Example:
Infix notation with parenthesis: (3 + 2) * (5 – 1)
Polish notation: * + 3 2 – 5 1
•Can be readily parsed into a syntax tree and stored in a
stack – Used by Interpreters
•LISP and other related languages use this notation to
define their syntax.
05/03/2025
JSPM's RSCOE
• Postfix notation is the notation in which
operators are placed after the corresponding
operands in the expression.
• Postfix notations can be used in intermediate
code generation in compiler design.
Example:
Infix notation: A + B
Postfix notation: AB+
Reverse Polish Notation or RPN (Postfix Notation)
05/03/2025
JSPM's RSCOE
Need of Prefix and Postfix Notations
• Can be evaluated faster than the infix notation.
• Prefix and Postfix notations are easier to parse for a
machine.
• There is never any question like operator precedence
and associativity.
Advantages of Postfix over Prefix Notations
• Postfix notation has fewer overheads of parenthesis. i.e.,
it takes less time for parsing.
• Postfix expressions can be evaluated easily as compared
to other notations
05/03/2025
JSPM's RSCOE
Applications of Stack
Expression Evaluation and Conversion
1. Infix to Postfix
2. Infix to Prefix
3. Postfix to Infix
4. Postfix to Prefix
5. Prefix to Infix
6. Prefix to Postfix
05/03/2025
JSPM's RSCOE
Infix Postfix
A + B A B +
A + B * C A B C * +
(A + B) * C A B + C *
A + B * C + D A B C * + D +
(A + B) * (C + D) A B + C D + *
A * B + C * D A B * C D * +
A + B * C  (A + (B * C))  (A + (B C *) )  A B C * +
A + B * C + D  ((A + (B * C)) + D )  ((A + (B C*) )+ D) 
((A B C *+) + D)  A B C * + D +
Infix to Postfix
05/03/2025
JSPM's RSCOE
Current
symbol
Operator
Stack
Postfix string
1 A A
2 * * A
3 ( * ( A
4 B * ( A B
5 + * ( + A B
6 C * ( + A B C
7 * * ( + * A B C
8 D * ( + * A B C D
9 ) * A B C D * +
10 + + A B C D * + *
11 E + A B C D * + * E
12 A B C D * + * E +
Expression:
A * (B + C * D) + E
becomes
A B C D * + * E +
Postfix notation
is also called as
Reverse Polish
Notation (RPN)
Infix to Postfix Rules
05/03/2025
JSPM's RSCOE
Infix to postfix conversion
•Use a stack for processing operators (push and pop
operations).
•Scan the sequence of operators and operands from left
to right and perform one of the following:
•output the operand,
•push an operator of higher precedence,
•pop an operator and output, till the stack top
contains operator of a lower precedence and push the
present operator.
05/03/2025
JSPM's RSCOE
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top,
push the incoming operator onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the
stack.
4. If the incoming symbol is a right parenthesis, pop the
stack and print the operators until you see a left
parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top
of the stack, push it on the stack.
05/03/2025
JSPM's RSCOE
The algorithm steps
6. If the incoming symbol has equal precedence with the
top of the stack, use association. If the association is left
to right, pop and print the top of the stack and then push
the incoming operator. If the association is right to left,
push the incoming operator.
7. If the incoming symbol has lower precedence than the
symbol on the top of the stack, pop the stack and print
the top operator. Then test the incoming operator against
the new top of stack.
8. At the end of the expression, pop and print all operators
on the stack. (No parentheses should remain.)
05/03/2025
JSPM's RSCOE
Infix to Postfix Conversion
Requires operator precedence information
Operands:
Add to postfix expression.
Close parenthesis:
pop stack symbols until an open parenthesis appears.
Operators:
Pop all stack symbols until a symbol of lower precedence appears. Then push
the operator.
End of input:
Pop all remaining stack symbols and add to the expression.
05/03/2025
JSPM's RSCOE
Infix To Prefix conversion using stack
Examples:
Input: A * B + C / D
Output: + * A B/ C D
Input: (A – B/C) * (A/K-L)
Output: *-A/BC-/AKL
05/03/2025
JSPM's RSCOE
How to convert infix expression to
prefix expression?
05/03/2025
JSPM's RSCOE
How to convert infix expression to
prefix expression?
To convert an infix expression to a prefix expression, we can
use the stack data structure. The idea is as follows:
Step 1: Reverse the infix expression. Note while reversing each
‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
Step 2: Convert the reversed infix expression to “nearly”
postfix expression.
While converting to postfix expression, instead of using pop
operation to pop operators with greater than or equal
precedence, here we will only pop the operators from stack
that have greater precedence.
Step 3: Reverse the postfix expression.
The stack is used to convert infix expression to postfix form.
05/03/2025
JSPM's RSCOE
Postfix to Infix conversion using stack
Examples:
Input : abc++
Output : (a + (b + c))
Input : ab*c+
Output : ((a*b)+c)
05/03/2025
JSPM's RSCOE
Postfix to Infix conversion using stack
1.While there are input symbol left
…1.1 Read the next symbol from the input.
2.If the symbol is an operand
…2.1 Push it onto the stack.
3.Otherwise,
…3.1 the symbol is an operator.
…3.2 Pop the top 2 values from the stack.
…3.3 Put the operator, with the values as arguments and
form a string.
…3.4 Push the resulted string back to stack.
4.If there is only one value in the stack
…4.1 That value in the stack is the desired infix string.
05/03/2025
JSPM's RSCOE
Postfix to Prefix conversion using stack
Examples:
Input : Postfix : AB+CD-*
Output : Prefix : *+AB-CD
Explanation : Postfix to Infix : (A+B) * (C-D)
Infix to Prefix : *+AB-CD
Input : Postfix : ABC/-AK/L-*
Output : Prefix : *-A/BC-/AKL
Explanation : Postfix to Infix : ((A-(B/C))*((A/K)-L))
Infix to Prefix : *-A/BC-/AKL
JSPM's RSCOE
Postfix to Prefix conversion using stack
Algorithm for Postfix to Prefix:
1. Read the Postfix expression from left to right
2. If the symbol is an operand, then push it onto the Stack
3. If the symbol is an operator, then pop two operands from the
Stack
Create a string by concatenating the two operands and the
operator before them.
string = operator + operand2 + operand1
And push the resultant string back to Stack
4. Repeat the above steps until end of Postfix expression.
JSPM's RSCOE
Prefix to Infix conversion using stack
Examples:
Input : Prefix : *+AB-CD
Output : Infix : ((A+B)*(C-D))
Input : Prefix : *-A/BC-/AKL
Output : Infix : ((A-(B/C))*((A/K)-L))
JSPM's RSCOE
Prefix to infix conversion using stack
Algorithm for Prefix to infix:
1. Read the Prefix expression in reverse order (from right to left)
2. If the symbol is an operand, then push it onto the Stack
3. If the symbol is an operator, then pop two operands from the
Stack
Create a string by concatenating the two operands and the
operator between them.
string = (operand1 + operator + operand2)
And push the resultant string back to Stack
4. Repeat the above steps until the end of Prefix expression.
JSPM's RSCOE
Prefix to postfix conversion using stack
Examples:
Input : Prefix : *+AB-CD
Output : Postfix : AB+CD-*
Explanation : Prefix to Infix : (A+B) * (C-D)
Infix to Postfix : AB+CD-*
Input : Prefix : *-A/BC-/AKL
Output : Postfix : ABC/-AK/L-*
Explanation : Prefix to Infix : (A-(B/C))*((A/K)-L)
Infix to Postfix : ABC/-AK/L-*
JSPM's RSCOE
Prefix to postfix conversion using stack
Algorithm for Prefix to Postfix:
1. Read the Prefix expression in reverse order (from
right to left)
2. If the symbol is an operand, then push it onto the
Stack
3. If the symbol is an operator, then pop two
operands from the Stack
Create a string by concatenating the two operands
and the operator after them.
string = operand1 + operand2 + operator
And push the resultant string back to Stack
4. Repeat the above steps until end of Prefix
expression.
*Example: postfix
expressions
Postfix notation is another way of writing
arithmetic expressions.
In postfix notation, the operator is written after
the two operands.
infix: 2+5 postfix: 2 5 +
Expressions are evaluated from left to right.
Precedence rules and parentheses are never
needed!!
*Example: postfix
expressions
(cont.)
*Postfix expressions:
Algorithm using stacks
(cont.)
*Postfix expressions:
Algorithm using stacks
WHILE more input items exist
Get an item
IF item is an operand
stack.Push(item)
ELSE
stack.Pop(operand2)
stack.Pop(operand1)
Compute result
stack.Push(result)
stack.Pop(result)
CS 201
*Bracket Matching Problem
Ensures that pairs of brackets are properly matched
• An Example: {a,(b+f[4])*3,d+f[5]}
• Bad Examples:
(..)..) // too many closing brackets
(..(..) // too many open brackets
[..(..]..) // mismatched brackets
CS 201
*Informal Procedure
Initialize the stack to empty
For every char read
if open bracket then push onto stack
if close bracket, then
return & remove most recent item
from the stack
if doesn’t match then flag error
if non-bracket, skip the char read
Example
{a,(b+f[4])*3,d+f[5]}
Stack
{
(
[
)
}
]
[ ]
05/03/2025
JSPM's RSCOE
Reverse string using stack
Follow the steps given below to reverse a string using stack.
1. Create an empty stack.
2. One by one push all characters of string to stack.
3. One by one pop all characters from stack and put them back to string.
Given a string, reverse it using stack.
Example:
Input: str = “abc”
Output: cba
05/03/2025
JSPM's RSCOE
Reverse string using stack
Follow the steps given below to reverse a string using stack.
1. Create an empty stack.
2. One by one push all characters of string to stack.
3. One by one pop all characters from stack and put them back to string.
Given a string, reverse it using stack.
Example:
Input: str = “abc”
Output: cba
05/03/2025
JSPM's RSCOE
Print Reverse a linked list using Stack
Follow the steps given below
First, insert all the elements in the stack
Print stack till stack is not empty
Given a linked list, print the reverse of it without modifying the list.
Example:
Input : 1 2 3 4 5 6
Output : 6 5 4 3 2 1
Input : 12 23 34 45 56 67 78
Output : 78 67 56 45 34 23 12
05/03/2025
JSPM's RSCOE
Reverse a number using stack
Follow the steps given below
The idea to do this is to extract digits of the number and push the digits on to a
stack. Once all of the digits of the number are pushed to the stack, we will start
popping the contents of stack one by one and form a number.
Given a number , write a program to reverse this number using stack.
Example:
Input : 365
Output : 563
Input : 6899
Output : 9986
Other Applications of Stacks
• Direct applications:
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Validate XML
• Indirect applications:
• Auxiliary data structure for algorithms
• Component of other data structures
CS 11001 : Programming and Data Structures Lecture #00: © DSamanta

Data Structures_Linear Data Structure Stack.pptx

  • 1.
    05/03/2025 JSPM's RSCOE Unit III:Stacks Dr. Rushali A. Deshmukh
  • 2.
    *CONTENTS LIFO Principle, Stack asan ADT, Representation and Implementation of Stack using Sequential and Linked Organization. Applications of Stack- Simulating Recursion using Stack, Arithmetic Expression Conversion and Evaluation, Reversing a String. Time complexity analysis of Stack operations JSPM's RSCOE
  • 3.
    05/03/2025 JSPM's RSCOE Concept ofStack ❖Stores a set of elements in a particular order ❖Stack principle: LAST IN FIRST OUT (LIFO). It means: The last element inserted is the first one to be removed ❖Example ❖Which is the first element to pick up?
  • 4.
    JSPM's RSCOE Stack Definition ❖Astack is an ordered collection of homogeneous items into which new items may be inserted and from which items may be deleted at one end, called the top of the stack. ❖Linear Data Structure ❖Restricted Data Structure - The deletion and insertion in a stack is done from top of the stack. ❖LIFO: (Last In, First Out), FILO (First In, Last Out)
  • 5.
  • 6.
    05/03/2025 JSPM's RSCOE Stack -Primitive operations ❖CreateEmptyStack(S): Create or make stack S be an empty stack ❖Push(S, x): Insert x at one end of the stack, called its top ❖Pop(S): If stack S is not empty; then delete the element at its top ❖Top(S): If stack S is not empty; then retrieve the element at its top ❖ IsFull(S): Determine if S is full or not. Return true if S is full stack; return false otherwise ❖IsEmpty(S): Determine if S is empty or not. Return true if S is an empty stack; return false otherwise.
  • 7.
  • 8.
  • 9.
    05/03/2025 JSPM's RSCOE Stack asADT objects: a finite ordered list with zero or more elements. methods: for all stack Stack, item element, max_stack_size positive ∈ ∈ ∈ integer Stack createS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size Boolean isFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) return TRUE else return FALSE
  • 10.
    05/03/2025 JSPM's RSCOE Stack push(stack,item) ::= if (IsFull(stack)) stack_full else insert item into top of stack and return Boolean isEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSE Element pop(stack) ::= if(IsEmpty(stack)) return else remove and return the item on the top of the stack.
  • 11.
    05/03/2025 JSPM's RSCOE #include <iostream> usingnamespace std; #define Maxsize 100 class Stack { int data[Maxsize]; int top; public: void create(); bool isfull(); bool isempty(); void push(int d); int pop(); int stacktop(); }; Stack Implementation using array in C++
  • 12.
    05/03/2025 JSPM's RSCOE int Stack::stacktop() { if(!isempty()) returndata[top]; else return -1; } bool Stack::isempty() { if(top == -1) { cout<<top; cout<<"stack is empty"; return true; } else return false; }
  • 13.
    05/03/2025 JSPM's RSCOE bool Stack::isfull() { if(top== Maxsize-1) { cout<<"stack is full"; return true; } else return false; } void Stack::create() { top = -1; } int Stack::pop() { if(!isempty()) return data[top--]; else return 0; }
  • 14.
    JSPM's RSCOE void Stack::push(intele) { if(!isfull()) data[++top]=ele; } int main() { // Write C++ code here Stack s1; s1.create(); s1.isempty(); s1.push(10); cout<<s1.stacktop(); s1.push(20); s1.push(30); cout<<s1.pop(); cout<<s1.pop(); cout<<s1.pop(); s1.isempty(); return 0; }
  • 15.
    05/03/2025 JSPM's RSCOE Complexity Analysisfor stack implementation using array: •: ◦push: O(1) ◦pop: O(1) ◦peek: O(1) ◦is_empty: O(1) ◦is_full: O(1) •:Space Complexity: O(n), where n is the number of items in the stack.
  • 16.
    05/03/2025 JSPM's RSCOE Advantages ofArray Implementation: •Easy to implement. •Memory is saved as pointers are not involved. Disadvantages of Array Implementation: •It is not dynamic i.e., it doesn’t grow and shrink depending on needs at runtime. [But in case of dynamic sized arrays like vector in C++, list in Python, ArrayList in Java, stacks can grow and shrink with array] implementation as well]. •The total size of the stack must be defined beforehand.
  • 17.
    Autumn 2016 Autumn 2016 top PUSHOPERATION Push using Linked List
  • 18.
    Autumn 2016 Autumn 2016 top POPOPERATION Pop using Linked List
  • 19.
    • In thearray implementation, we would: • Declare an array of fixed size (which determines the maximum size of the stack). • Keep a variable which always points to the “top” of the stack. • Contains the array index of the “top” element. • In the linked list implementation, we would: • Maintain the stack as a linked list. • A pointer variable top points to the start of the list. • The first element of the linked list is considered as the stack top. Autumn 2016 Autumn 2016 Basic Idea
  • 20.
    05/03/2025 JSPM's RSCOE Infix, Prefix,& Postfix Notations Infix Notation • The operator is between operands • A problem is that we need parentheses or precedence rules to handle more complicated expressions: For Example : a + b * c is (a + b) * c ? OR a + (b * c) ? How do you figure out the operands of an operator? Infix Notation - Operator Priority • Operators are assigned priorities priority(*) = priority(/) > priority(+) = priority(-) • When an operand lies between two operators, the operand associates with the operator that has higher priority.
  • 21.
    05/03/2025 JSPM's RSCOE Infix, Prefix,& Postfix Notations Infix Notation - Associativity •When an operand lies between two operators that have the same priority, the operand associates with the operator on the left or on the right a + b - c a * b / c / d
  • 22.
    05/03/2025 JSPM's RSCOE Polish Notation(Prefix Notation) • Introduced by the Polish logician Lukasiewicz • Operators are placed on the left of their operands. • If the operator has a defined fixed number of operands, the syntax does not require brackets or parenthesis to lessen ambiguity. Example: Infix notation with parenthesis: (3 + 2) * (5 – 1) Polish notation: * + 3 2 – 5 1 •Can be readily parsed into a syntax tree and stored in a stack – Used by Interpreters •LISP and other related languages use this notation to define their syntax.
  • 23.
    05/03/2025 JSPM's RSCOE • Postfixnotation is the notation in which operators are placed after the corresponding operands in the expression. • Postfix notations can be used in intermediate code generation in compiler design. Example: Infix notation: A + B Postfix notation: AB+ Reverse Polish Notation or RPN (Postfix Notation)
  • 24.
    05/03/2025 JSPM's RSCOE Need ofPrefix and Postfix Notations • Can be evaluated faster than the infix notation. • Prefix and Postfix notations are easier to parse for a machine. • There is never any question like operator precedence and associativity. Advantages of Postfix over Prefix Notations • Postfix notation has fewer overheads of parenthesis. i.e., it takes less time for parsing. • Postfix expressions can be evaluated easily as compared to other notations
  • 25.
    05/03/2025 JSPM's RSCOE Applications ofStack Expression Evaluation and Conversion 1. Infix to Postfix 2. Infix to Prefix 3. Postfix to Infix 4. Postfix to Prefix 5. Prefix to Infix 6. Prefix to Postfix
  • 26.
    05/03/2025 JSPM's RSCOE Infix Postfix A+ B A B + A + B * C A B C * + (A + B) * C A B + C * A + B * C + D A B C * + D + (A + B) * (C + D) A B + C D + * A * B + C * D A B * C D * + A + B * C  (A + (B * C))  (A + (B C *) )  A B C * + A + B * C + D  ((A + (B * C)) + D )  ((A + (B C*) )+ D)  ((A B C *+) + D)  A B C * + D + Infix to Postfix
  • 27.
    05/03/2025 JSPM's RSCOE Current symbol Operator Stack Postfix string 1A A 2 * * A 3 ( * ( A 4 B * ( A B 5 + * ( + A B 6 C * ( + A B C 7 * * ( + * A B C 8 D * ( + * A B C D 9 ) * A B C D * + 10 + + A B C D * + * 11 E + A B C D * + * E 12 A B C D * + * E + Expression: A * (B + C * D) + E becomes A B C D * + * E + Postfix notation is also called as Reverse Polish Notation (RPN) Infix to Postfix Rules
  • 28.
    05/03/2025 JSPM's RSCOE Infix topostfix conversion •Use a stack for processing operators (push and pop operations). •Scan the sequence of operators and operands from left to right and perform one of the following: •output the operand, •push an operator of higher precedence, •pop an operator and output, till the stack top contains operator of a lower precedence and push the present operator.
  • 29.
    05/03/2025 JSPM's RSCOE The algorithmsteps 1. Print operands as they arrive. 2. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto the stack. 3. If the incoming symbol is a left parenthesis, push it on the stack. 4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you see a left parenthesis. Discard the pair of parentheses. 5. If the incoming symbol has higher precedence than the top of the stack, push it on the stack.
  • 30.
    05/03/2025 JSPM's RSCOE The algorithmsteps 6. If the incoming symbol has equal precedence with the top of the stack, use association. If the association is left to right, pop and print the top of the stack and then push the incoming operator. If the association is right to left, push the incoming operator. 7. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop the stack and print the top operator. Then test the incoming operator against the new top of stack. 8. At the end of the expression, pop and print all operators on the stack. (No parentheses should remain.)
  • 31.
    05/03/2025 JSPM's RSCOE Infix toPostfix Conversion Requires operator precedence information Operands: Add to postfix expression. Close parenthesis: pop stack symbols until an open parenthesis appears. Operators: Pop all stack symbols until a symbol of lower precedence appears. Then push the operator. End of input: Pop all remaining stack symbols and add to the expression.
  • 32.
    05/03/2025 JSPM's RSCOE Infix ToPrefix conversion using stack Examples: Input: A * B + C / D Output: + * A B/ C D Input: (A – B/C) * (A/K-L) Output: *-A/BC-/AKL
  • 33.
    05/03/2025 JSPM's RSCOE How toconvert infix expression to prefix expression?
  • 34.
    05/03/2025 JSPM's RSCOE How toconvert infix expression to prefix expression? To convert an infix expression to a prefix expression, we can use the stack data structure. The idea is as follows: Step 1: Reverse the infix expression. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘. Step 2: Convert the reversed infix expression to “nearly” postfix expression. While converting to postfix expression, instead of using pop operation to pop operators with greater than or equal precedence, here we will only pop the operators from stack that have greater precedence. Step 3: Reverse the postfix expression. The stack is used to convert infix expression to postfix form.
  • 35.
    05/03/2025 JSPM's RSCOE Postfix toInfix conversion using stack Examples: Input : abc++ Output : (a + (b + c)) Input : ab*c+ Output : ((a*b)+c)
  • 36.
    05/03/2025 JSPM's RSCOE Postfix toInfix conversion using stack 1.While there are input symbol left …1.1 Read the next symbol from the input. 2.If the symbol is an operand …2.1 Push it onto the stack. 3.Otherwise, …3.1 the symbol is an operator. …3.2 Pop the top 2 values from the stack. …3.3 Put the operator, with the values as arguments and form a string. …3.4 Push the resulted string back to stack. 4.If there is only one value in the stack …4.1 That value in the stack is the desired infix string.
  • 37.
    05/03/2025 JSPM's RSCOE Postfix toPrefix conversion using stack Examples: Input : Postfix : AB+CD-* Output : Prefix : *+AB-CD Explanation : Postfix to Infix : (A+B) * (C-D) Infix to Prefix : *+AB-CD Input : Postfix : ABC/-AK/L-* Output : Prefix : *-A/BC-/AKL Explanation : Postfix to Infix : ((A-(B/C))*((A/K)-L)) Infix to Prefix : *-A/BC-/AKL
  • 38.
    JSPM's RSCOE Postfix toPrefix conversion using stack Algorithm for Postfix to Prefix: 1. Read the Postfix expression from left to right 2. If the symbol is an operand, then push it onto the Stack 3. If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator before them. string = operator + operand2 + operand1 And push the resultant string back to Stack 4. Repeat the above steps until end of Postfix expression.
  • 39.
    JSPM's RSCOE Prefix toInfix conversion using stack Examples: Input : Prefix : *+AB-CD Output : Infix : ((A+B)*(C-D)) Input : Prefix : *-A/BC-/AKL Output : Infix : ((A-(B/C))*((A/K)-L))
  • 40.
    JSPM's RSCOE Prefix toinfix conversion using stack Algorithm for Prefix to infix: 1. Read the Prefix expression in reverse order (from right to left) 2. If the symbol is an operand, then push it onto the Stack 3. If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator between them. string = (operand1 + operator + operand2) And push the resultant string back to Stack 4. Repeat the above steps until the end of Prefix expression.
  • 41.
    JSPM's RSCOE Prefix topostfix conversion using stack Examples: Input : Prefix : *+AB-CD Output : Postfix : AB+CD-* Explanation : Prefix to Infix : (A+B) * (C-D) Infix to Postfix : AB+CD-* Input : Prefix : *-A/BC-/AKL Output : Postfix : ABC/-AK/L-* Explanation : Prefix to Infix : (A-(B/C))*((A/K)-L) Infix to Postfix : ABC/-AK/L-*
  • 42.
    JSPM's RSCOE Prefix topostfix conversion using stack Algorithm for Prefix to Postfix: 1. Read the Prefix expression in reverse order (from right to left) 2. If the symbol is an operand, then push it onto the Stack 3. If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator after them. string = operand1 + operand2 + operator And push the resultant string back to Stack 4. Repeat the above steps until end of Prefix expression.
  • 43.
    *Example: postfix expressions Postfix notationis another way of writing arithmetic expressions. In postfix notation, the operator is written after the two operands. infix: 2+5 postfix: 2 5 + Expressions are evaluated from left to right. Precedence rules and parentheses are never needed!!
  • 44.
  • 45.
  • 46.
    *Postfix expressions: Algorithm usingstacks WHILE more input items exist Get an item IF item is an operand stack.Push(item) ELSE stack.Pop(operand2) stack.Pop(operand1) Compute result stack.Push(result) stack.Pop(result)
  • 47.
    CS 201 *Bracket MatchingProblem Ensures that pairs of brackets are properly matched • An Example: {a,(b+f[4])*3,d+f[5]} • Bad Examples: (..)..) // too many closing brackets (..(..) // too many open brackets [..(..]..) // mismatched brackets
  • 48.
    CS 201 *Informal Procedure Initializethe stack to empty For every char read if open bracket then push onto stack if close bracket, then return & remove most recent item from the stack if doesn’t match then flag error if non-bracket, skip the char read Example {a,(b+f[4])*3,d+f[5]} Stack { ( [ ) } ] [ ]
  • 49.
    05/03/2025 JSPM's RSCOE Reverse stringusing stack Follow the steps given below to reverse a string using stack. 1. Create an empty stack. 2. One by one push all characters of string to stack. 3. One by one pop all characters from stack and put them back to string. Given a string, reverse it using stack. Example: Input: str = “abc” Output: cba
  • 50.
    05/03/2025 JSPM's RSCOE Reverse stringusing stack Follow the steps given below to reverse a string using stack. 1. Create an empty stack. 2. One by one push all characters of string to stack. 3. One by one pop all characters from stack and put them back to string. Given a string, reverse it using stack. Example: Input: str = “abc” Output: cba
  • 51.
    05/03/2025 JSPM's RSCOE Print Reversea linked list using Stack Follow the steps given below First, insert all the elements in the stack Print stack till stack is not empty Given a linked list, print the reverse of it without modifying the list. Example: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12
  • 52.
    05/03/2025 JSPM's RSCOE Reverse anumber using stack Follow the steps given below The idea to do this is to extract digits of the number and push the digits on to a stack. Once all of the digits of the number are pushed to the stack, we will start popping the contents of stack one by one and form a number. Given a number , write a program to reverse this number using stack. Example: Input : 365 Output : 563 Input : 6899 Output : 9986
  • 53.
    Other Applications ofStacks • Direct applications: • Page-visited history in a Web browser • Undo sequence in a text editor • Chain of method calls in the Java Virtual Machine • Validate XML • Indirect applications: • Auxiliary data structure for algorithms • Component of other data structures CS 11001 : Programming and Data Structures Lecture #00: © DSamanta