0% found this document useful (0 votes)
8 views

DS - Lecture 05 - Stacks

Uploaded by

abhitp.ug21.ec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

DS - Lecture 05 - Stacks

Uploaded by

abhitp.ug21.ec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

DATA STRUCTURES

(CS3501)

Anil Kumar Dudyala,


Asst. Prof, Dept. of CSE, NIT Patna.
[email protected];

A K Dudyala NITP -- CS3501 1


The Course

DATA STRUCTURES

A K Dudyala
2
NITP -- CS3501
STACKS

A K Dudyala
3
NITP -- CS3501
UNIT IV: Stacks

Basics of Stack data structure, Implementation of stack using array and linked list,
Operations on stacks, Applications of Stacks, Notations – infix, prefix and postfix,
Conversion and evaluation of arithmetic expressions using Stacks.

A K Dudyala
4
NITP -- CS3501
Data structure-stack [5]
[4]
• Stack is a linear data structure in which the insertion and deletion operations are
[3]
performed at only one end.
[2]
• In a stack, adding and removing of elements are performed at a single position which [1]
is known as "top”. [0] top (presently)

• That means, a new element is added at top of the stack and an element is removed
from the top of the stack.
D->C->B->A
• Inserting an element into stack at top is said to be PUSH operation.
The order in
top D which elements
• Deleting element from top of the stack is said to be POP operation.
gets removed
C from the stack
• In stack, the insertion and deletion operations are performed based on LIFO (Last In Disk-A
Disk-B B
First Out) principle or FILO (First in Last Out) Disk-C
Disk-D A
A K Dudyala
5
NITP -- CS3501
Example of inserting elements into stack (PUSH operation)
Insert the elements 10,45,12,16,35 and 50 into an empty stack

top 16
top 12 12
top 45 45 45
10 10 10 10
top
top

top 50
top 35 35
16 16
12 12
45 45
Inserting (push)
10 10 A K Dudyala
6
NITP -- CS3501
Example of Removing elements from the stack (POP operation)
Deleted elements { } Deleted elements {50 , 35, 16, 12}
Deleted elements {50 , 35, 16, 12, 45}
Deleted elements {50}
Deleted elements {50 , 35, 16, 12, 45, 10}
Deleted elements {50, 35}
Deleted elements {50 , 35, 16}

top 50
35 top 35
16 16 top 16
12 12 12 top 12
45 45 45 top 45
45
10 10 10 10 top 10
10
top
In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out) principle.
A K Dudyala
7
NITP -- CS3501
Application of stack (Importance of stack)
When a function call is invoked, calling function will be pushed onto the stack. It will
remain in the stack until called function finishes. GHI() DEF
{ ABC
When a function main calls
…..
function ABC, then main is main

inserted onto the top of stack. DEF()
ABC }
main will be removed once {
ABC is completed main …..
After GHI execution is

int main() main ABC() completed, DEF will be
GHI();
{ { removed from the top of
}
….. DEF(); stack.
… }
ABC(); ABC
….
… main

main
}

A K Dudyala
8
NITP -- CS3501
Stack Operations
• Standard operations
• Push
• To insert an element at the top of stack

• Pop
• To remove element from the top of stack

• Display (user defined)


• To display the elements of stack
• Usually once it is done stack will be empty.

• Peak (user defined)


• Returns the top of the element

A K Dudyala
9
NITP -- CS3501
Applications of STACK
• Reversing a list

• Parentheses checking

• Conversion of an infix expression into a postfix expression

• Evaluation of a postfix expression

• Conversion of an infix expression into a prefix expression

• Evaluation of a prefix expression

• Recursion

• Tower of Hanoi

• DFS technique
A K Dudyala
10
NITP -- CS3501
Implementation of Stack

• Simple Array based Implementation.

• Linked list Implementation.

A K Dudyala
11
NITP -- CS3501
Implementation of STACK using Arrays

A K Dudyala
12
NITP -- CS3501
STACK ADT (Array Based)
// Define the stack
#define MAX 100
Element Type stack[MAX];
int top = -1;

// Define the set of operations on stack


void push(Element Type[], int, Element Type);
Element Type pop(stack, top);
void Display(Element Type [], int)
Element Type Peak(Element Type [], int);

A K Dudyala
13
NITP -- CS3501
Push operation
step - 1 : IF top = Max-1
PUSH(Element Type *stack, int top, Element Type value) Display “ OVERFLOW”
Go to step-4
step – 2: top++
• push() is a function used to insert an element into the stack. Step – 3: stack[top] = value
Step - 4: End
• The new element is always inserted at top position.

• Step 1 - Check whether stack is FULL. (top = = SIZE-1 or not)

• Step 2 - If stack is FULL, then display "Stack OVERFLOW!!!


Insertion is not possible!!!" and terminate the function.

• Step 3 - If stack is NOT FULL, then increment top value by one


(top++) and set stack[top] to value (stack[top] = value). Time Complexity = O(1)

A K Dudyala
14
NITP -- CS3501
step - 1 : IF top = Max-1
Display “ OVERFLOW” Insert 20,45,12,16, and 35
Go to step-4
step – 2: top++ Push(stack, top, 20) Push(stack, top, 45) Push(stack, top, 12)
Step – 3: stack[top] = value
Step - 4: End

• #define MAX 4 [3] [3] [3] [3]


• int stack[MAX]; [2] [2] [2] 12
top=2 [2]
• int top=-1; [1] [1] 45 [1] 45
top=1 [1]
• push(int *stack, int top, int ele) 20
[0] top=0 [0] 20 20
{ [0] [0]
top=-1
if(top==MAX-1)
{ printf(“\n Stack Overflow”); Push(stack, top, 16) Push(stack, top, 35)
}
else
top=3 16 [3]
{ top=top+1;
12 [2]
stack[top]=ele; Stack Overflow
45 [1]
}
20 [0] A K Dudyala 15
} NITP -- CS3501
POP operation step - 1 : IF top = -1
Display “ UNDERFLOW”
• pop() is a function used to delete an element from the stack. Go to step-5
step – 2: x = stack[top]
• In a stack, the element is always deleted from top position. Step – 3: top--
Step – 4: return x
• Visiting element from the stack is possible by calling pop(). Step - 5: End
• We can use the following steps to pop an element from the
stack...
• Step 1 - Check whether stack is EMPTY. (top = = -1)
• Step 2 - If it is EMPTY, then display “UNDERFLOW!
Deletion is not possible!" and terminate the function.
• Step 3 - If it is NOT EMPTY, then delete stack[top] and
decrement top value by one (top--). Time Complexity = O(1)
A K Dudyala
16
NITP -- CS3501
step - 1 : IF top = -1 Deleted elements { } pop(stack, top) pop(stack, top) pop(stack, top)
Display “ UNDERFLOW” Deleted elements {35} Deleted elements {35, 16} Deleted elements {35, 16, 12}
Go to step-6
step – 2: x = stack[top]
Step – 3: top-- top 35 [4]
Step – 4: return x 16 [3] [3]
Step - 5: End top 16
12 [2] [2] top 12 [2]
12
int pop(int *stack, int top) 45 [1] [1] 45 [1] top 45 [1]
45
{ int val; 10 [0] 10 [0] 10 [0] 10 [0]
pop(stack, top) pop(stack, top)
if(top = = -1) Deleted elements {35, 16, 12, 45} Deleted elements {35, 16, 12, 45, 10}
printf(“\n underflow\n”);
else pop(stack, top)
{ val=stack[top];
top=top-1;
return val;
} Underflow
top 10 [0]
} top
A K Dudyala
NITP -- CS3501 17
STACK PROGRAM
void main()
{ int value, choice, ele;
#include<stdio.h> while(1)
{ clrscr(); printf("\n\n***** MENU *****\n");
#include<conio.h> printf(“1. Push\n 2. Pop\n 3. Display\n 4. Peak 5.Exit");
#define SIZE 05 printf("\nEnter your choice: "); scanf("%d",&choice);
switch(choice)
int stack[SIZE], top = -1; {case 1: printf("Enter the value to be insert: ");
void push(int); scanf("%d",&value); push(value); break;
case 2: ele=pop(); printf(“\n %d is deleted”,ele); break;
int pop(); case 3: display(); break;
void display(); case 4: ele=peak(); printf(“\n The top element is: %d”, ele); break;
case 5: exit(0);
int peak() default: printf("\nWrong selection Try again!!!");
}// switch – case
}// while
} // main
A K Dudyala
18
NITP -- CS3501
STACK OPERATIONS (LOGIC)
int pop()
void push(int value) { int element;
{ if(top == SIZE-1) if(top == -1)
printf("\n Stack Overflow … “); printf("\n Stack Underflow”);
else else
{ top++; stack[top] = value; { element=stack[top]; top--;
printf("\n Insertion success!!!"); } return element; }
} }
int peak()
void display() { int val;
{ if(top == -1) if (top==-1) printf(“\n Stack Underflow”);
printf("\n Stack Underflow"); else
else { val=pop();
{ int i; push(val);
printf("\n Stack elements are:\n"); return val;
for(i=top; i>=0; i--) }
printf(“%d ", stack[i]); } }
} Time Complexity = O(1)
Time Complexity = O(n) A K Dudyala
19
NITP -- CS3501
Implementation of STACK using Linked Lists

A K Dudyala
20
NITP -- CS3501
Implementation of STACK using Linked Lists
• The other way of implementing the stack is using the Linked List (SLL/ CSLL/
DLL/ CDLL).

• The push operation is the insertion of node into the linked list at the beginning.

• The pop operation is the deletion of node from the beginning (the header/ top
node)

A K Dudyala
21
NITP -- CS3501
STACK ADT (Linked List Based (SLL))
// Define node
typedef struct Node STACK;
struct Node
{ int data; // Assume we are storing integer data
STACK *next;
}*top = NULL; // Initially stack is empty
// Define the set of operations on stack
void push(STACK *, int);
int pop(STACK *);
void Display(STACK *)
int Peak(STACK *);

A K Dudyala
22
NITP -- CS3501
Push operation
Time Complexity = O(1)
PUSH(STACK *stack, int top, Element Type value)

• push() is a function used to insert an element into the stack.

• The new element is always inserted at the beginning of the list and is pointed by top
(In List it is head / start) .

• Step 1 - create a new_node. If new_node creation failed, then display "Stack OVERFLOW!!!
Insertion is not possible!!!" and terminate the function.

• Step 2 - If stack is NOT FULL, then insert the value and assign NULL to new_nodenext.

• Step 3 – if top == NULL, then assign new_node to top and terminate the function;

• Step 4 – If top != NULL, then assign top to new_nodenext and new_node to top;

A K Dudyala
23
NITP -- CS3501
PUSH(STACK *top, int value) new_node
new_node 10 NULL
1. new_nodenext=top
step1
x1000 x2000 x1000
x1000
// No Stack Overflow top 2. top=new_node
step4 x2000 20 x3000
new_node
x500 x2000
step 2 10 NULL x1000
30 NULL
top
x500 NULL x3000
step3
top new_node
x500 NULL 10 NULL
x1000
x1000

A K Dudyala 24
NITP -- CS3501
STACK OPERATION - PUSH (Logic)

void push(STACK *top, int value)


{ STACK *new_node;
new_node = (STACK *) malloc (sizeof(STACK));
if(new_node == NULL)
printf("\n Stack Overflow … “);
else
{ new_node  data = value; new_nodenext = NULL;
if(top == NULL) // This is the first node
top = new_node;
else // There exist some nodes
{ new_node next = top;
top = new_node;
printf("\n Insertion success!!!");
}
}
Time Complexity O(1)

A K Dudyala
25
NITP -- CS3501
Pop operation
POP(STACK *top)
Time Complexity = O(1)
• pop() is a function used to delete an element from the top of the stack.

• The element is always deleted at the beginning of the list and is pointed by top
(In List it is head / start) .

• Step 1 - If top is NULL, then display "Stack UNDERFLOW!!! Deletion is not


possible!!!" and terminate the function.

• Step 2 - If stack is NOT EMPTY, then declare a pointer temp and assign top to temp.

• Step 3 – if topnext == NULL, then assign NULL to top, delete the temp and terminate the
function;

• Step 4 – If topnext != NULL, then assign tempnext to top and delete temp;
A K Dudyala
26
NITP -- CS3501
POP(STACK *top)
top
step1 // Display Stack Underflow
NULL

x500
top
top x2000 20 x3000
step 2 x2000 step 4
30 NULL x500
x2000
x500 x2000 temp
temp
30 NULL
x3000

top top
X3000 30 NULL
step3 NULL
x500 x3000
x500

A K Dudyala 27
NITP -- CS3501
STACK OPERATION - POP (Logic)

int pop(STACK *top)


{
int element;
STACK *t;
if(top == NULL)
printf("\n Stack Underflow”);
else
{
element = topdata;
t = top;
top = top next;
free(t);
return element;
}
}

A K Dudyala
28
NITP -- CS3501
STACK OPERATIONS (Logic)

void display(STACK *top)


{ if(top == NULL) int peak(STACK *top)
{ int val;
printf("\n Stack Underflow"); if (top = = NULL) printf(“\n Stack Underflow”);
else else
{ val=top  data;
{ STACK *t = top; return val;
printf("\n Stack elements are:\n"); }
}
while(t != NULL) Time Complexity = O(1)
{ printf(“%d ", tdata);
t = tnext; } // while
} // else
} // display
Time Complexity = O(n) A K Dudyala
29
NITP -- CS3501
Parenthesis checking
• {(((([]))))} // Check the parenthes is are balanced or not

• if char is „(„ or „{„ or „[„ then we push it onto the top of stack.

• If char is „)‟ or „}‟ or „]‟ then we perform pop operation and if the popped character

matches with the starting bracket then fine otherwise parenthesis are not balanced and

terminate the task.

• If char is the end of string and if stack is empty, then it is balanced.

• In other cases, it is said to imbalanced.

A K Dudyala
30
NITP -- CS3501
ASSIGNMENT (Graded one)
1. Write the algorithm/pseudo code to implement stack using doubly linked list.

2. Demonstrate how to check the balancing of the following parenthesis expressions using stack
i. (a+b*(c/d)+e*(-f))
ii. a[(b*(c+d))]
iii. a/(b/(c)

3. Write the algorithm/pseudo code for how to reverse the given string using the stack operations push
and pop. Also demonstrate with an example.

4. Write the algorithm/pseudo code to convert the given decimal number into binary using the stack.
Also demonstrate with an example.

5. Write the algorithm/pseudo code to check the given string is palindrome or not using stack. Also
demonstrate with an example.

A K Dudyala
31
NITP -- CS3501
Notations – infix, prefix and postfix
• Any arithmetic expression consists of operators and operands.

• The way we write the arithmetic expression is called notation;

• There are three different notations used to write the arithmetic expression.
1. Infix Expression

2. Prefix Expression

3. Postfix expression

• We can convert the expression in one notation to another notation.

A K Dudyala
32
NITP -- CS3501
Infix Notation
• An expression is said to be in infix notation if the operators in the expression are placed in
between the operands on which the operator works.

• For example - a + b * c

• In the above example the operator is * is placed between the operands on which this
operator works, here b and c.

• Infix expressions are easy for humans to read, write and understand, but it is not the case
for computing devices.

• It is costly (in terms of space and time) to process the infix expressions in algorithms.

A K Dudyala
33
NITP -- CS3501
Prefix Notation
• An expression is said to be in prefix notation if the operators in the expression are
placed before the operands on which the operator works.

• For example - +a*bc

• In the above example the operator is * is placed before the operands on which this
operator works, here b and c, similarly the + is placed before a and the result of
(b*c).

• Prefix notation is also called as Polish notation.

A K Dudyala
34
NITP -- CS3501
Postfix Notation
• An expression is said to be in postfix notation if the operators in the expression are
placed after the operands on which the operator works.

• For example - abc*+

• In the above example the operator is * is placed after the operands on which this
operator works, here b and c, similarly the + is placed after a and the result of
(b*c).

• Postfix notation is also called as Reverse Polish notation.

• Widely used notation for evaluating the expressions.

A K Dudyala
35
NITP -- CS3501
Evaluation of expressions
• When evaluating the arithmetic expression two things need be considered:
1. The precedence of the operator - If any operand is present in-between two different operators, the
precedence (priority) of the one operator over the other decides which operator should use the operand first
or which operator to be evaluated first. For example in the arithmetic expression a + b * c the operand b is
surrounded by the operators * and +. In computer languages the * enjoying the higher precedence than the +,
so * takes b first.
2. The Associativity of the operator - It resolves the ties between the same precedence of operators in the
arithmetic expression, by considering whether the operators are evaluated from left to right or right to left.
For example in the expression a* b * c, here b is surrounded by two * operators, So which * should take b
first or which multiplication must be done first? It is decided by the associativity of *. So in computer
languages * is a left associative, so the first * will be performed first (multiply a and b first then the result
will be multiplied by c).

• It is not advantageous to evaluate the infix expressions, so first convert them to postfix or prefix
and then compute the expressions.

A K Dudyala
36
NITP -- CS3501
Precedence and Associativity of operators
Operator Description Associativity Precedence
() Parenthesis 1(function calls) Left to Right 14
[] Brackets (array subscript)
. Members selection via object name
 Member selection via pointer
++ -- Post increment and post decrement
++ -- Pre increment and pre decrement Right to Left 13
+ - Unary plus or minus
! ~ Logical negation and bitwise complement
(type) Casting type
* Dereference
& Address
Sizeof Size in bytes
* / % Arithmetic multiplication, division, modulus Left to Right 12
+ - Arithmetic addition, subtraction Left to Right 11
<< >> Bitwise shift left, shift right Left to Right 10
< <= Relational less than, less than or equal to Left to Right 9
> >= Relational greater than, greater than or equal to
1. Parenthesis are used to override the precedence of operators and such parenthesis expressions can be nested and evaluated from inner to outer
A K Dudyala
37
NITP -- CS3501
Precedence and Associativity of operators
Operator Description Associativity Precedence
== != Relational equal to, not equal to Left to Right 8
& Bitwise AND Left to Right 7
^ Bitwise Exclusive OR Left to Right 6
| Bitwise Inclusive OR Left to Right 5
&& Logical AND Left to Right 4
|| Logical OR Left to Right 3
?: Ternary condition Right to Left 2
= Assignment Right to Left 1
+= -+ Addition/Subtraction Assignment
*= /= Multiplication/Division Assignment
%= &= Modulus/Bitwise AND assignment
^= |= Bitwise Exclusive/ Inclusive Assignment
<<= >>= Bitwise Shift Left/Right Assignment
, Comma Left to Right 0

1. Parenthesis are used to override the precedence of operators and such parenthesis expressions can be nested and evaluated from inner to outer
A K Dudyala
38
NITP -- CS3501
Infix to postfix Conversion
1. Read all the symbols one by one from left to right in the given Infix Expression.

2. If the reading symbol is operand, then immediately send it to the output.

3. If the reading symbol is left parenthesis '(', then Push it on to the Stack.

4. If the reading symbol is right parenthesis ')', then Pop all the contents of stack until
respective left parenthesis is popped and print each popped symbol to the output.

5. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However,
first pop the operators which are already on the stack that have higher or equal precedence
than the current operator and output them. If open parenthesis is there on top of the stack
then push the operator into stack, even though the precedence of ( is more than any other
operator and it is the exceptional case.

6. If the input is over, so pop all the remaining symbols from the stack and output them.
A K Dudyala
39
NITP -- CS3501
Infix to postfix Conversion (Example)
Consider the infix arithmetic expression: a * (b + c + d)
1 Input (infix expression)
a * (b + c + d) a
Output (postfix expression)
a is an operand
Action - Output a
top STACK

2 Input (infix expression)


a
a * (b + c + d) Output (postfix expression)
• * is an operator,
• Action - push it into stack *
top
after removing the higher or
equal priority operators STACK
from the top of the stack
A K Dudyala
40
NITP -- CS3501
Infix to postfix Conversion (Example)
3 Input (infix expression)
a
a * (b + c + d) Output (postfix expression)

top (
• ( is an open parenthesis *
top *
• Action - push it into
stack STACK STACK

4
Input (infix expression)
a * (b + c + d) ab

top ( Output (postfix expression)


b is an operand, so output b *
STACK

A K Dudyala
41
NITP -- CS3501
Infix to postfix Conversion (Example)
Input (infix expression)
5
a * (b + c + d) a b
• + is an operator, Output (postfix expression)
• Action - push it into stack after removing top +
the higher or equal priority operators from (
the top of the stack. Present operator on *
stack is ( and it has higher precedence than
+, but for ( we have exception, so push + STACK
into stack,

6 abc
Input (infix expression) top +
Output (postfix expression)
a * (b + c + d) (
*

c is an operand, so output c STACK

A K Dudyala
42
NITP -- CS3501
Infix to postfix Conversion (Example)
Input (infix expression)
7 a bc+
a * (b + c + d)
• + is an operator, top + Output (postfix expression)
• Action - push it into stack after removing (
the higher or equal priority operators top (
*
from the top of the stack. Present *
operator on stack is + and it has equal STACK
precedence with the input symbol +, so STACK
pop the + from stack and output.

abc +

• + is an operator, Output (postfix expression)


• Action – Now present top of the stack is ( and it has higher top +
precedence than input symbol +, +, but for ( we have an (
exception, so push + into stack
*
STACK
A K Dudyala
43
NITP -- CS3501
Infix to postfix Conversion (Example)
Input (infix expression)
8
a * (b + c + d) a bc+ d

top + Output (postfix expression)


d is an operand, so output d (
*
STACK

9 Input (infix expression)

a * (b + c + d) abc+d+

Output (postfix expression)


• ) is an operator,
• Action – Pop all the contents of stack until
respective left parenthesis is popped and top *
send each popped symbol to the output.
STACK

A K Dudyala
44
NITP -- CS3501
10 Infix to Postfix Conversion (Example)
Input (infix expression)
a * (b + c + d) a bc+ d+*

Input is over so pop all the Output (postfix expression)


remaining symbols from the stack
and output them.

top STACK

A K Dudyala
45
NITP -- CS3501
Infix to Postfix conversion (Logic) void push(char *stack, int top, char e)
{

#include<stdio.h> if(top==size-1)
int prio(char op)
#include<string.h> printf("\n stack overflow");
{
#include<ctype.h> if(op = = '+‟ || op= = '-') else
return 1;
stack[++top]=e;
#define size 100 if(op = = '*' || op = = „/‟ || op==„%‟)
char stack[size]; return 2; }
if(op == „(„ )
int top=-1; return 0; char pop(char *stack, int top)
void push(char *, int, char); else {printf(“Wrong operator”); exit(0);} {
}
char pop(char *, int); // Assume our expression contains only these operators if(top==-1)
int prio(char op); printf("\n stack is underflow");
else
return stack[top--];
}
A K Dudyala
46
NITP -- CS3501
Infix to Postfix conversion (Logic)
void main()
{ char ie[100], pe[100]; int i, j=0;
printf("\n Enter infix expression: "); gets(ie);
for(i=0; ie[i]!='\0‟; i++)
{ if(ie[i]=='(„) push(ie[i]); // open parenthesis is pushed into the stack
else if( (ie[i] >= „a‟ && ie[i] <= „z‟) || (ie[i] >= „0‟ && ie[i] <= „9‟)) {pe[j++]=ie[i]; } //operand
else if(ie[i]==„)‟) // if it is closed parenthesis then pop all symbols from the stack upto open parenthesis encountered in the stack
{while(stack[top]!=„(„) { pe[j++]=pop(stack, top); } // Assume the given infix expression is parenthesis balanced one
pop(); }
else // if it is an operator
{ while(top > -1 && (prio(stack[top])>=prio(ie[i]) ) {pe[j++]=pop();}
push(ie[i]); }
}
while(top>-1) {pe[j++]=pop(); } // Leftover symbols from the stack are popped
pe[j]='\0‟;
printf("the infix expression %s converted to %s postfix expression",ie, pe);
}
A K Dudyala
47
NITP -- CS3501
Infix to Prefix Conversion
1. Reverse the given infix expression, for example the reverse of the infix expression a + b *c
is c * b + a. When reversing the parenthesis „)‟ will become „(„ and „(„ will become „)‟
(applicable to all types of brackets)

2. Apply the infix to postfix conversion algorithm on the reversed infix expression. For the
above example the resultant postfix expression is: cb*a+

3. Reverse the obtained postfix expression, and is the required prefix expression for the given
infix expression. For the above example, the infix expression is +a*bc

A K Dudyala
48
NITP -- CS3501
Prefix to Infix Conversion
1. Reverse the given prefix expression, for example the reverse of the prefix expression *cd is
dc*

2. Read the character by character of the reversed prefix expression and repeat the step 3 and 4
till there are no characters in the reversed prefix expression .

3. If the character read is an operand then push the operand into the stack. (push d and c)

4. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string p1 op p2 to stack.
(push c *d )

5. Now the value in the stack is the required infix expression. (c*d)

A K Dudyala
49
NITP -- CS3501
Prefix to Postfix Conversion
1. Reverse the given prefix expression, for example the reverse of the prefix expression *cd is
cd*.

2. Read the character by character of the reversed prefix expression and repeat the step 3 and 4
till there are no characters in the reversed prefix expression .

3. If the character read is an operand then push the operand into the stack. (push d and c)

4. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string p1 p2 op to stack.
(push c d * )

5. Now the value in the stack is the required infix expression. (c d *)

A K Dudyala
50
NITP -- CS3501
Postfix to Infix Conversion
1. Read the character by character of the given postfix expression and repeat the step 3 and 4
till there are no characters in the postfix expression. For example assume the postfix
expression ab+;

2. If the character read is an operand then push the operand into the stack. (push a and b)

3. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string p2 op p1 to stack.
(push a * b )

4. Now the value in the stack is the required infix expression. (a * b)

A K Dudyala
51
NITP -- CS3501
Postfix to Prefix Conversion
1. Read the character by character of the given postfix expression and repeat the step 2 and 3
till there are no characters in the postfix expression. For example assume the postfix
expression ab+;

2. If the character read is an operand then push the operand into the stack. (push a and b)

3. If the character read is an operator, op, then pop the top two symbols from the stack, the
first one is p1, and the second one is p2. Push the concatenated string op p2 p1 to stack.
(push a * b )

4. Now the value in the stack is the required postfix expression. (*a b)

A K Dudyala
52
NITP -- CS3501
Examples
S.No Infix Expression Prefix Expression Postfix Expression
1 a+b*c +a*bc a b c*+
2 (a + b) * (c + d) * + a b + c d ab+cd+*
3 a*b + c * d +*ab*cd ab*cd*+
4 a+b+c+d +++abcd ab+c+d+
5 (a + b) * c – d -*+a b c d ab + c * d-
6 a+b-c -+a b c ab + c -

A K Dudyala
53
NITP -- CS3501
Evaluation of Postfix Expression
Infix exp: ( 5 + 3 ) * ( 8 -2)
Postfix: 5 3 + 8 2 - *

Algorithm
1. Scan the symbols one by one from left to right in the given Postfix Expression

2. If the reading symbol is operand, then push it on to the Stack.

3. If the reading symbol is binary operator (+ , - , * , / etc.,), then perform two pop operations and
do the operation specified by the reading symbol (if it is * do multiplication, etc) using the two
popped operands and push the result back on to the stack.

4. Repeat steps 2 & 3 till the postfix expression completes.

5. Finally! perform a pop operation and display the popped value as final result.

A K Dudyala
54
NITP -- CS3501
Evaluations of postfix Conversion (Example)
Infix exp: ( 6 + 2 ) * ( 8 - 2)
Postfix: 6 2 + 8 2 - *
Reading Stack
Reading Stack Reading Stack Symbol
Symbol Symbol

8
Initially 2 (operand) t
(operand) t o 8
o 2 push(stack, top, 8) p
push(stack, top, 2) p
8
6
t
o
p
+ 2 t
(operator) (operand) o 2
p
6 pop the top two push(stack, top, 2) 8
(operand) two operands from
push(stack, top, 6) t Stack t 8
o
6 op1 = pop(stack, top) //2
o 8
p p
op2 = pop(stack, top) // 6
op3 = op2 + op1 // 8
push(op3)
A K Dudyala
55
NITP -- CS3501
Evaluations of postfix Conversion (Example)
Infix exp: ( 6 + 2 ) * ( 8 - 2)
Postfix: 6 2 + 8 2 - *
Reading Stack
Symbol

-
(operator)
pop the top two
two operands from stack t

op1 = pop(stack, top) //2


o
p
6
op2 = pop(stack, top) //8
8
The final value is : 48
op3 = op2 - op1 // 6
push(stack, top, op3)

*
(operator)
pop the top two
operands from stack
op1 = pop(stack, top) // 6
t
op2 = pop(stack, top // 8 o 48
op3 = op2 * op1 p
push(op3)
A K Dudyala
56
NITP -- CS3501
#include<stdio.h>
#include<string.h>
Postfix Evaluation void push(int e)
#include<ctype.h> {
#define size 100 If(top==size-1)
else if( isdigit(pe[i])) printf("\n stack overflow");
int stack[size];
push(pe[i]-'0'); else
int top=-1;
else stack[++top]=e;
void push(int);
{ op2=pop(); }
int pop();
op1=pop();
void main() switch(pe[i])
{ char pe[30]; int pop()
{case '+‘ : push(op1+op2);break;
int i,v,op1,op2; {
case '-‘ : push(op1-op2);break;
printf("\n enter any if(top==-1)
case '*‘ : push(op1*op2);break;
postfix expression"); printf("\n stack underflow");
case '/': push(op1/op2);break;
gets(pe); else
case '%‘ : push(op1%op2);break;
for(i=0;pe[i]!='\0';i++) return stack[top--];
default: printf("\n invalid operation");
{ if(isalpha(pe[i])) }
}
{printf("\n enter value for %c", pe[i]); }
scanf("%d",&v); }
push(v); printf(“\n The result is: %d",stack[top]);
} Postfix: X 4 + Y Z - *
}
X= 5, Y=8, Z=2
A K Dudyala
57
NITP -- CS3501
Thank You

A K Dudyala
58
NITP -- CS3501

You might also like