Você está na página 1de 14

STACK is a linear data structure which provides insertions(push) and deletions(pop) from one

end of the stack called Top of stack. The various applications of stacks are listed below:
1. Evaluation of postfix expression.
2. Conversion of Infix into Postfix expression.
3. Balancing of Symbols.
4. Function Calling.
EVALUATION OF POSTFIX EXPRESSION:

Postfix Evaluation of an Expression using Stacks


The standard notation used to represent mathematical expressions is called
infix notation. You should be very familiar with it already because it is
almost exclusively used in books and thought in schools. Just to be clear,
the typical example of infix expression is:
(2 + 3) - 7 / 9

However, there exists two other yet significantly less popular notations
called prefix and postfix. In this article we will concentrate on the later and
describe what it is and how to evaluate it using computer.
Postfix notation

Postfix notation (also known as Reverse Polish Notation or RPN in short) is


a mathematical notation in which operators follow all of its operands. It is
different from infix notation in which operators are placed between its
operands. The previously mentioned infix expression can be represented
using postfix notation like this:
23+79/-

To evaluate this expression we take two first numbers 2 and 3, add them
and remember the result; then we take the next two numbers 7 and 9,

divide them and remember the result. At last we take the two remembered
values and we subtract them to obtain the final result.
While postfix notation may seem less natural and straightforward, it has
several advantages which made it popular in computing. The main reason is
that postfix expressions are generally easier to calculate on computers than
the equivalent infix expressions and do not require any brackets to define
the order of operations (assuming that every operator has fixed number of
operands). Additionally, the ease of processing results in significantly
simpler and more efficient algorithms. This made postfix notation very
popular in representing intermediate results of computations.
Algorithm

The algorithm to evaluate any postfix expression is based on stack and is


given below:
1.
2.

Initialize empty stack


For every token in the postfix expression (scanned from left to right):
1.
If the token is an operand (number), push it on the stack
2.
Otherwise, if the token is an operator (or function):
1.
Check if the stack contains the sufficient number of values
(usually two) for given operator
2.
If there are not enough values, finish the algorithm with
anerror
3.
Pop the appropriate number of values from the stack
4.
Evaluate the operator using the popped values and push
the single result on the stack
3.
If the stack contains only one value, return it as a final result of the
calculation
4.
Otherwise, finish the algorithm with anerror

Example

As an example we will try to evaluate the following postfix expression:


234+*6-

which can be represented in infix notation like this:


2 * (3 + 4) - 6

The exact steps of the algorithm are put in the table below:

Input token

Operation

Stack contents
(top on the right)

Push on the
stack

Push on the
stack

2, 3

Push on the
stack

2, 3, 4

Add

2, 7

Details

Pop two
values: 3 and
4 and push the
result 7 on the

stack

Multiply

14

Push on the
stack

14, 6

(End of tokens)

Subtract

(Return the
result)

Pop two
values: 2 and 7
and push the
result 14 on
the stack

Pop two
values: 14 and
6 and push the
result 8 on the
stack

Pop the only


value 8 and
return it

The contents of the stack in theStack contents column is represented


from left to right with the rightmost values being on the top of the stack.
When there are no more tokens in the input, the contents of the stack is
checked. If there is only one value, it is the result of the calculation. If there
are no values or if there are many, the passed input expression was not a
valid postfix expression.
/* program for evaluation of a post fix expression using Stacks. */
#include<stdio.h>//preprocessor
#include<string.h>//preprocessor
//#include<stdlib.h>//preprocessor

#include<math.h>//preprocessor
char p[20]; //input string
float s[10];// stack
signed int top=-1,i=0,j=0,n;
float a,b,c,x;
//function declarations
signed int push(float);
float pop();
void main()//main function
{
printf("\n\tEnter An expression in post fix notation\n\t");
scanf("%s",p);
n=strlen(p);//find length of expression
while(p[i]!='\0')
{
switch(p[i])
{
case '+':
printf("\n in case +");
b=pop();
a=pop();
c=a+b;
push(c);
break;
case '-':
printf("\n in case -");
b=pop();
a=pop();
c=a-b;
push(c);
break;
case '*':
printf("\n in case *");
a=pop();
b=pop();
c=a*b;
push(c);
break;
case '/':
printf("\n in case /");
b=pop();
a=pop();
c=a/b;
push(c);
break;
case '^':
printf("\n in case ^");
b=pop();

a=pop();
c=pow(a,b);
push(c);
break;
default :
printf("\n in default case");
/*we have to typecast p[i] which is character
to float so that we can push it on to float
type stack*/
x = (float)(p[i]-'0');
printf("\n\tThe x value is %f \t",x);
push(x);
break;
}//end Switch
i++;
}//end While
printf("\n\tThe evaluation of given expression is
%8.4f\n\t",s[top]);
}//end main
//function definitions
int push(float x)//push function
{
top++;//increment top
s[top]=x;//assign x to stack of top
s[top+1]='\0';
return 0;
}//end push
float pop()//pop function
{
float item;
item=s[top];//assign stack of top to item
s[top]='\0';
top--;//decrement top
return (item);
}//end pop
/*
C:\Dev-Cpp\stack>poteval2.exe
Enter An expression in post fix notation
54321^*/in default case
The x value is 5.000000
in default case
The x value is 4.000000
in default case
The x value is 3.000000
in default case
The x value is 2.000000
in default case
The x value is 1.000000
in case ^

in case *
in case /
in case The evaluation of given expression is
*/

4.3333

Infix to Postfix Using a Stack


Stacks are widely used in the design and implementation of compilers. For example, they are
used to convert arithmetic expressions from infix notation to postfix notation. An infix
expression is one in which operators are located between their operands. This is how we are
accustomed to writing expressions in standard mathematical notation. In postfix notation, the
operator immediately follows its operands. Examples of infix expressions are:
a*b
f*gb
d/e*c+2
d / e * (c + 2)
The corresponding postfix expressions (assuming Java precedence rules) are:
ab*
fg*b
de/c*2+
de/c2+*
In a postfix expression, a binary operator is applied to the two immediately preceding operands.
A unary operator is applied to the one immediately preceding operand. Notice that the operands
in a postfix expression occur in the same order as in the corresponding infix expression. Only the
position of the operators is changed. A useful feature of postfix is that the order in which
operators are applied is always unambiguous. That is, there is only a single interpretation of any
postfix expression. This is not true of infix. For example, the meaning of the infix expression a +
b * c is unclear. Does it mean (a + b) * c or a + (b * c)? Without parentheses or additional rules,
we cannot say. In Java, precedence rules dictate that multiplication is performed before addition;
we say that multiplication takes precedence over addition. The corresponding postfix
expression is a b c * +, and there is no ambiguity. It is explicit that the multiplication operator

applies to the immediately two preceding operands b and c. The addition operator is then applied
to operand a and the result (b * c). If we had meant the expression (a + b) * c, we would have
written it in postfix notation as a b + c *. Now the + operation is applied to the two operands a
and b, and * is performed on the two operands c and the result (a + b).

Because of the existence of this unique interpretation, some compilers first convert
arithmetic expressions from the standard infix notation to postfix to simplify code generation. To
convert an infix expression to postfix, we must use a stack to hold operators that cannot be
processed until their operands are available.
Assume that we are given as input the infix string a + b * c d. This is equivalent to the
parenthesized infix arithmetic expression (a + (b * c)) d. To convert this to postfix format, we
scan the input from left to right. If the next symbol in the input stream is an operand (for
example, a) it is placed directly into the output stream without further processing.
Input: a + b * c d

Output: a

opStack: empty

If the next symbol in the input string is an operator (for example, +), then we compare the
precedence of this operator to the one on top of a stack called opStack, short for operator stack,
which is initialized to empty at the start of the scan. If opStack is empty or if the precedence of
the next operator in the input stream is greater than the precedence of the one on top of opStack,
then we push the operator from the input string onto opStack and continue.
Input: a + b * c d

Output: a

opStack: +

Lets explain what is happening a little more intuitively. We are trying to locate the highestprecedence operation to determine which operation to perform next. As long as the operators
being scanned are increasing in precedence, we cannot do anything with our infix expression.
Instead, we stack them and continue scanning the input string.
Input: a + b * c d

Output: a b

opStack: +

Output: a b

opStack: +
*

Output: a b c

opStack: +
*

Output: a b c

opStack: +
*

Input: a + b * c d

Input: a + b * c d

Input: a + b * c d

At this point, we encounter the operator, whose precedence is lower than the *, the
operator on top of the stack. We now pop operators from opStack until either (1) opStack is
empty, or (2) the precedence of the operator on top of opStack is strictly less than that of the
current operator in the input string. In this case, we pop both the * and + operators and place
them into the output stream:
Input: a + b * c d

Output: a b c *

opStack: +

Output: a b c * +

opStack:
empty

Input: a + b * c d

This scanning process continues until we come to the end of the input. Then, any remaining
operators on opStack are popped into the output and the algorithm terminates.
Input: a + b * c d

Output: a b c * +

opStack:

Output: a b c * + d

opStack:

Output: a b c * + d

opStack:
empty

Input: a + b * c d

Input: a + b * c d

The algorithm has produced the expression a b c * + d , the correct postfix representation of
the original input.
In this example, a stack was the right structure to hold operators from the input stream
because of the nature of the algorithm. Operators must be saved until we determine their
proper location, and then they are placed into the output stream in the reverse order of their
occurrence in the input. Again, this is a perfect match with the LIFO model of a stack.

LTC :
// Program for converting infix expression to postfix form using
stacks
#include<stdio.h>//preprocessor
#include<string.h>//preprocessor
#include<stdlib.h>//preprocessor
int preceed(char c);
void push(char c);

char pop();
char stk[30];
int tos =-1;
int main()
{
int i,j=0,n,u,v;
char infix[30],postfix[30];
char c;
printf("\n enter the infix expression:");
scanf("%s",infix);
n=strlen(infix);
for(i=0;i<n;i++)
{
if((infix[i]>= 'a' && infix[i]<= 'z') || (infix[i]>= 'A' &&
infix[i]<= 'Z'))
{ postfix[j] = infix[i];
j=j+1;
} //end of if
else
if( infix[i]=='^'||infix[i]=='*'||infix[i]=='/'
||infix[i]=='+'||infix[i]=='-')
{ u = preceed(stk[tos]);
v = preceed(infix[i]);
while(v<= u && stk[tos]!= '(')
{ postfix[j]=pop();
j=j+1;
u = preceed(stk[tos]);
}
push(infix[i]);
}//end of else if 1
else
if( infix [i] == '(')
{ push(infix[i]);
} // end of else if 2
else
if (infix[i] == ')')
{ c = pop();
while(c != '(')
{ postfix[j]= c;
j=j+1;
c= pop();
} // end of while
}// end of if else 3
else
{
printf("\n\tTHE EQUATION HAS ERROR");
exit(0);
}//end else
} // end of for
while(tos!=-1)
{ postfix[j]= pop();
j=j+1;
}
postfix[j]='\0';
printf("\nThe equation in POSTFIX notation is: %s\n",postfix);
}//end main

int preceed(char c)//preceed function


{
int v;
switch(c)
{
case '^': v=3;
break;
case '*':
case '/': v=2;
break;
case '+':
case '-': v=1;
break;
default : v=0;
break;
}//end switch
return(v);
}//end preced()
void push(char c)
{ tos++;
stk[tos] = c;
}
char pop()
{ char val;
val = stk[tos];
tos--;
return(val);
}
/*
C:\Dev-Cpp\stack>intopo.exe
enter the infix expression:a*(b+c)/d
The equation in POSTFIX notation is: abc+*d/
*/

Balancing Symbols using Stacks

This program uses stack to check whether an expression is


balanced or not. The expression is parsed character by
character and when opening bracket is found, it is inserted into
the stack. When the equivalent closing bracket is found, the
stack is popped. If the stack is totally empty after parsing the
entire expression, then the expression isbalanced
expression.

#include < stdio.h >


#include < conio.h >

#define max 50
void main()
{
char stk[max],exp[100];
int top,i;
clrscr();
top = -1;
printf("\nEnter an infix expression ");
gets(exp);
for(i=0; exp[i] != '\0'; i++)
{
if( exp[i]=='(' || exp[i] =='[' || exp[i] == '{' )
{
top++;
stk[top]= exp[i];
}
else
if ( exp[i] == ')' )
{
if( stk[top] == '(' )
top--;
}
else
{
printf("Unbalanced exp");
exit(0);
}
}
else
if ( exp[i] == ']' )
{
if( stk[top] == '[' )
top--;
else
{
printf("Unbalanced exp");
exit(0);
}
}
else
if ( exp[i] == '}' )
{
if( stk[top] == '{' )
top--;
else
{
printf("Unbalanced exp");
exit(0);
}
}
} // for
if( top == -1 )

printf("Exp is balanced");
else
printf("Exp is not balanced");
} // main

Você também pode gostar