You are on page 1of 58

DATA STRUCTURES

(CS3401)

Dr. Somaraju Suvvari,


Asst. Prof, Dept. of CSE, NIT Patna.
somaraju@nitp.ac.in;
soma2402@gmail.com;
Dr Somaraju Suvvari NITP -- CS3401 1
The Course

DATA STRUCTURES

Dr Somaraju Suvvari
2
NITP -- CS3401
STACKS

Dr Somaraju Suvvari
3
NITP -- CS3401
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.

Dr Somaraju Suvvari 4
NITP -- CS3401
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 [1]
[0] top (presently)
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. D->C->B->A


The order in
• Inserting an element into stack at top is said to be PUSH operation. top D which elements
gets removed
• Deleting element from top of the stack is said to be POP operation. C from the stack
Disk-A
• Disk-B B
In stack, the insertion and deletion operations are performed based on LIFO (Last
Disk-C
In First Out) principle or FILO (First in Last Out) Disk-D A
Dr Somaraju Suvvari
5
NITP -- CS3401
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
45 45 45
top
10 10 10 10
top
top

50
top
top 35 35
16 16
12 12
45 45 Inserting (push)
10 10 Dr Somaraju Suvvari 6
NITP -- CS3401
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 12
top
45 45 45 45 top 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. Dr Somaraju Suvvari 7
NITP -- CS3401
Application of stack (Importance of stack)
When a function call is invoked, calling function will be pushed onto the stack. It will be
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
… completed, DEF will be
int main() main ABC() GHI(); removed from the top of
{ { }
….. DEF(); stack.
… }
ABC(); ABC
….
main

main
}

Dr Somaraju Suvvari 8
NITP -- CS3401
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


Dr Somaraju Suvvari 9
NITP -- CS3401
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
Dr Somaraju Suvvari 10
NITP -- CS3401
Implementation of Stack

• Simple Array based Implementation.

• Linked list Implementation.

Dr Somaraju Suvvari 11
NITP -- CS3401
Implementation of STACK using Arrays

Dr Somaraju Suvvari
12
NITP -- CS3401
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);

Dr Somaraju Suvvari 13
NITP -- CS3401
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)

Dr Somaraju Suvvari 14
NITP -- CS3401
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
• int top=-1; top=2 [2]
[1] [1] 45 [1] 45
• push(int *stack, int top, int ele)
top=1 [1]
20 20
[0] top=0
[0] 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] Dr Somaraju Suvvari 15
} NITP -- CS3401
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)

Dr Somaraju Suvvari 16
NITP -- CS3401
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 – 4: top-- top 35 [4]
Step – 5: return x 16 [3] [3]
Step - 6: End top 16
12 [2] 12 [2] top 12 [2]
45 [1] 45 [1] 45 [1] top 45 [1]
int pop(int *stack, int top)
10 [0] 10 [0] 10 10
{ int val; [0] [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
Dr Somaraju Suvvari
NITP -- CS3401 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
Dr Somaraju Suvvari
18
NITP -- CS3401
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)
Dr Somaraju Suvvari 19
NITP -- CS3401
Implementation of STACK using Linked Lists

Dr Somaraju Suvvari
20
NITP -- CS3401
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)

Dr Somaraju Suvvari 21
NITP -- CS3401
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 *);

Dr Somaraju Suvvari 22
NITP -- CS3401
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;
Dr Somaraju Suvvari 23
NITP -- CS3401
PUSH(STACK *top, int value)

10
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
10 NULL x1000 x500 x2000
step 2
30 NULL
top
x500 NULL x3000
step3
top new_node
x500 NULL 10 NULL
x1000
x1000

Dr Somaraju Suvvari 24
NITP -- CS3401
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)

Dr Somaraju Suvvari 25
NITP -- CS3401
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;
Dr Somaraju Suvvari 26
NITP -- CS3401
POP(STACK *top)
top
step1 NULL // Display Stack Underflow
x500
top
top x2000 20 x3000
step 2 x2000 30 NULL step 4
x500
x2000
x500 x2000
temp 30 NULL
x3000

top top
step3 NULL
X3000 30 NULL
x500 x3000
x500

Dr Somaraju Suvvari 27
NITP -- CS3401
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;
}
}

Dr Somaraju Suvvari 28
NITP -- CS3401
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) Dr Somaraju Suvvari 29
NITP -- CS3401
Parenthesis checking
• {(((([]))))} // Check the parenthesis 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 is the

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.

Dr Somaraju Suvvari 30
NITP -- CS3401
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.
Dr Somaraju Suvvari 31
NITP -- CS3401
Notations – infix, prefix and postfix
• Any arthematic 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 athematic expression.
1. Infix Expression

2. Prefix Expression

3. Postfix expression

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

Dr Somaraju Suvvari 32
NITP -- CS3401
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.

Dr Somaraju Suvvari 33
NITP -- CS3401
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.

Dr Somaraju Suvvari 34
NITP -- CS3401
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.


Dr Somaraju Suvvari 35
NITP -- CS3401
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 the 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 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.

Dr Somaraju Suvvari
36
NITP -- CS3401
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
Dr Somaraju Suvvari 37
NITP -- CS3401
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 Dr Somaraju Suvvari
38
NITP -- CS3401
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.
Dr Somaraju Suvvari
39
NITP -- CS3401
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
Dr Somaraju Suvvari 40
NITP -- CS3401
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

Input (infix expression)


4
a * (b + c + d) ab

top ( Output (postfix expression)


b is an operand, so output b *
STACK

Dr Somaraju Suvvari 41
NITP -- CS3401
Infix to postfix Conversion (Example)
Input (infix expression)
5
a * (b + c + d) a b
• + is an operator, Output (postfix expression)
top +
• Action - push it into stack after removing
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

Dr Somaraju Suvvari 42
NITP -- CS3401
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

Dr Somaraju Suvvari 43
NITP -- CS3401
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

Dr Somaraju Suvvari 44
NITP -- CS3401
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

Dr Somaraju Suvvari 45
NITP -- CS3401
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");
if(op = = '+’ || op= = '-') else
#include<ctype.h>
return 1;
#define size 100 if(op = = '*' || op = = ‘/’ || op==‘%’) stack[++top]=e;
return 2; }
char stack[size];
if(op == ‘(‘ )
int top=-1; return 0; char pop(char *stack, int top)
else {printf(“Wrong operator”); exit(0);} {
void push(char *, int, char);
}
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--];
}
Dr Somaraju Suvvari 46
NITP -- CS3401
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);
}
Dr Somaraju Suvvari 47
NITP -- CS3401
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

Dr Somaraju Suvvari
48
NITP -- CS3401
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 infix 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)

Dr Somaraju Suvvari
49
NITP -- CS3401
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 infix 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 *)

Dr Somaraju Suvvari
50
NITP -- CS3401
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)

Dr Somaraju Suvvari
51
NITP -- CS3401
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)

Dr Somaraju Suvvari
52
NITP -- CS3401
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 -

Dr Somaraju Suvvari 53
NITP -- CS3401
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.

Dr Somaraju Suvvari
54
NITP -- CS3401
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

t
2 8
Initially
t o 8
(operand) o 2 p
push(stack, top, 2) p
(operand) 8
6 push(stack, top, 8)
t
o
p
+ t
o 2
p
(operator) 2
pop the top two 8
6 (operand)
two operands from 8
t t push(stack, top, 2)
(operand)
o
6 Stack o 8
p p
op1 = pop(stack, top) //2
push(stack, top, 6)
op2 = pop(stack, top) // 6
op3 = op2 + op1 // 8
push(op3)

Dr Somaraju Suvvari 55
NITP -- CS3401
Evaluations of postfix Conversion (Example)
Infix exp: ( 6 + 2 ) * ( 8 - 2)
Postfix: 6 2 + 8 2 - *
Reading Stack

Symbol

-
(operator)
pop the top two t

two operands from stack


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

*
(operator)
pop the top two
operands from stack
t
op1 = pop(stack, top) // 6 o 48
op2 = pop(stack, top // 8 p
op3 = op2 * op1
push(op3)
Dr Somaraju Suvvari 56
NITP -- CS3401
#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
Thank You

Dr Somaraju Suvvari
58
NITP -- CS3401

You might also like