0% found this document useful (0 votes)
21 views16 pages

Unit III - Postfix Evaluation and Balancing Symbols

Uploaded by

pk6048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views16 pages

Unit III - Postfix Evaluation and Balancing Symbols

Uploaded by

pk6048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

21CSC201J

DATA STRUCTURES AND ALGORITHMS

UNIT-3

Topic : POSTFIX EVALUATION AND


BALANCING SYMBOLS
Postfix evaluation
 Postfix notation (also known as Reverse Polish Notation) is a way to represent an expression,

where operators follow their corresponding operands. Evaluating an expression represented as

postfix notation can easily be done using the stack data structure.

 It is used in computers because it is faster than other types of notations (such as infix notation) as

parentheses are not required to represent them.

 Stack data structure is used to efficiently evaluate Postfix Expression.

 Time and Space complexity for evaluating postfix expression using stack are

 Time complexity - O(N)

 Space complexity -O(N)


Input-Output

Input - A string consisting of numeric values along with operator symbols (*, /, +, -, etc) is
given as the input.

 Output - The result obtained by solving the given input is required to be printed.

Examples of Postfix Expression Evaluation

Example 1 :

Input - 2 3 * 4 5 + * Output - 54

Example 2 :

Input - 5 2 3 * * Output - 30
Algorithm for Evaluating Postfix Expression

Suppose P is an expression that we want to evaluate


1.Scan P from left to right and repeat steps 2 and 3 for each element pf P until null is encountered.
2.If an operand is encountered, put it on Stack.
3.If an operator © is encountered, then:
(a) Remove the two top elements of STACK, where A is the top element and B is the next to top
element.
(b) Evaluate B and A.
(c) Place the result on the STACK.
4.Result equal to the top element on STACK.
5.Exit.
At last, stack will consist of a single element .i.e. the result after evaluating the postfix expression.
Evaluating a Postfix Expression-Psuedocode
Opndstk = the empty stack;
/* scan the input string */
/* element at a time into symb */
While(not end of input)
symb = next imput character;
if(symb is an operand)
push(opnstk,symb);
else{
/* symb is an operator */
opnd2= pop(opndstk);
opnd1=pop(opndstk);
value=result of applying symb to opnd1 and opnd2;
push(opndstk,value);
} /* end else */
} /* end while */
Return(opndstk);
Suppose we are ask to solve below postfix expression 623+-382/+*2$3+

+ 49 3 52 52
Program to evaluate postfix expression
#include <stdio.h>
#include<math.h>
#define maxcols 80
#define true 1
#define false 0
Double eval(char[]);
double pop(struct stack*);
Void push(struct stack*, double);
int empty(struct stack*);
int isdigit(char);
double oper(int,double,double);
Void main( ) {
char expr[maxcols];
int position =0;
while((expr[position++]=getchar())!=‘\n’);
expr[--position]=‘\0’;
printf(“\n The original postfix expression is “,expr);
printf(“\n%f”,eval(expr)); }
Program to evaluate postfix expression(Contd…)
else
Struct stack{ {
int top; /* operator */ Opnd2= pop(&opndstk);
double items[maxcols]; Opnd1=pop(&opndstk); Value=oper(c,opnd1,opnd2);
} Push(&opndstk,value);
double eval(char exp[]) }
{ }
int c, position; Return(pop(&opndstk));
double opnd1,opnd2,value; } /* end eval */
struct stack opndstk;
opndstk=-1; int isdigit(char symb)
for(position=0;(c=expr[position])!=‘\0’;position++) {
{ return(symb>=‘0’ && symb<=‘9’);
if(isdigi( c )) }
/* operand – convert the character representation */
/* of the digit into double and push it onto the stack */
Push(&opndstk, (double)(c-’0’));
}
Program to evaluate postfix expression(Contd…)

double oper(int symb, double op1, double op2)


{
switch(symb)
{
case ‘+’ : return(op1+op2);
case ‘-’ : return(op1-op2);
case ‘*’ : return(op1*op2);
case ‘/’ : return(op1/op2);
case ‘$’ : return(pow(op1,op2));
default : printf(“ illegal operation”);
exit(1);
} /* switch */
} /* end oper */
Conclusion

 In postfix notation, the operator appears after the operands.


 It does not require the use of parentheses and therefore it is faster when
compared to other notations.
 Stack data structure is used for evaluation of postfix expression efficiently.
Balancing Symbols
Why Balancing Symbols?
 One of the most important applications of stacks is to check if the parentheses are balanced in a
given expression. The compiler generates an error if the parentheses are not matched.

 Here are some of the balanced and unbalanced expressions:

Consider the above mentioned unbalanced expressions:

 The first expression ( a + b is unbalanced as there is no closing parenthesis given.


 The second expression [ ( c - d * e ] is unbalanced as the closed round parenthesis is not given.
 The third expression { [ ( ] ) } is unbalanced as the nesting of square parenthesis and the round
parenthesis are incorrect.
Steps to find whether a given expression is
balanced or unbalanced

 Input the expression and put it in a character stack.

 Scan the characters from the expression one by one.

 If the scanned character is a starting bracket ( ‘ ( ‘ or ‘ { ‘ or ‘ [ ‘), then push it to the stack.

 If the scanned character is a closing bracket ( ‘ ) ’ or ‘ } ’ or ‘ ] ’ ), then pop from the stack and if the

popped character is the equivalent starting bracket, then proceed. Else, the expression is unbalanced.

 After scanning all the characters from the expression, if there is any parenthesis found in the stack or

if the stack is not empty, then the expression is unbalanced.

 Now, let us see a program to check balanced parentheses in the given expression.
Let's understand the above algorithm through an example.
Suppose expression is 2 * ( 6 + 5 )

Solution:
 First, the x variable is initialized by 0.
 The scanning starts from the variable '2', when it encounters '(' then the 'x' variable gets incremented by
1 and when the x reaches to the last symbol of the expression, i.e., ')' then the 'x' variable gets
decremented by 1 and it's final value becomes 0.
 We have learnt in the above algorithm that if x is equal to 0 means the expression is balanced;
 Therefore, the above expression is a balanced expression.
C Code
#include<stdio.h> void pop()
#include<stdlib.h> {
#include<string.h> if (s.top == - 1)
#define MAX 20 {
struct stack printf ("Stack is Empty\n");
{ }
char stk[MAX]; else
int top; {
}s; s.top = s.top - 1; // Pop the char and decrement top
void push(char item) }}
{
if (s.top == (MAX - 1)) int main(){
printf ("Stack is Full\n"); char exp[MAX];
else int i = 0;
{ s.top = -1;
s.top = s.top + 1; // Push the char and increment top printf("\nINPUT THE EXPRESSION : ");
s.stk[s.top] = item; scanf("%s", exp);
}}
C Code (Contd…)
for(i = 0;i < strlen(exp);i++)
{
if(exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
{
push(exp[i]); // Push the open bracket
continue;
}
else if(exp[i] == ')' || exp[i] == ']' || exp[i] == '}') // If a closed
bracket is encountered
{
if(exp[i] == ')')
{
if(s.stk[s.top] == '(')
{
pop(); // Pop the stack until closed bracket is found
}
else
{
printf("\nUNBALANCED EXPRESSION\n");
break;
}}

You might also like