Vous êtes sur la page 1sur 12

Infix to Postfix Conversion

Infix Expression Postfix


Expression
a+b ab+
a+b-c abc-+
a+b*c abc*+
a+(b*c) abc*+
(a+b)*c ab+c*
(a+b)*(c-d) ab+cd-*
a+b*c-d abc*d-+
a+(b*c)-d abc*d-+
Infix to Postfix Conversion
Infix Expression Postfix Expression
a*b-c+d ab*cd+-
(a*b)-c+d ab*cd+-
a+b*c/d abcd/*+
(a+b)*c/d ab+cd/*

a-(b/c+(d abc/def*%g/+h*-
%e*f)/g)*b
Convert: a - ( b/c + (d % e* f ) /
Infix Character g) * h Postfix expression
Stack
scanned
a a
- - a
( -( a
b -( ab
/ -(/ ab
c -(/ abc
+ -(+ abc/
( -(+( abc/
d -(+( abc/d
% -(+(% abc/d
e -(+(% abc/de
* -(+(%* abc/de
Convert: a - ( b/c + (d % e* f ) /
g) * h
Infix Character Stack Postfix expression
scanned
f -(+(%* abc/def
) -(+ abc/def*%
/ -(+/ abc/def*%
g -(+/ abc/def*%g
) - abc/def*%g/+
* -* abc/def*%g/+
h -* abc/def*%g/+h
abc/def*%g/
+h*-
Infix to Postfix Conversion
Program
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>

char stk[ 20 ];
int top=-1;

int priority (char);


int push(char c);
int pop();
Infix to Postfix Conversion
Program Continues

void main()
{
char infix[20], postfix[20], ch;
int i, j, l;
clrscr();
printf(\nEnter the String Expression :");
gets(infix);
l=strlen(infix);
for(i=0 ,j=0; i < l; i++)
{
if ( isalpha (infix [ i ] ) )
postfix [ j++ ] = infix [ i ];
else
{
if ( infix [ i ] == '( )
push (infix [ i ] );
else if ( infix [ i ] == ') )
while ( ( ch = pop() ) != '( )
postfix [ j ++] = ch;
else
{
while (priority(infix [ i ]) <
priority( stk[ top ] ))
postfix[ j++ ] = pop() ;
push( infix [ i ] ) ;
}
}
}
while ( top != -1)
postfix[ j++ ]= pop();
postfix[ j ]= '\0';

printf( "\n Equivalent infix to postfix is:%s", postfix);

getch();

} // main closing
Infix to Postfix Conversion
Push and Pop Operation on
Stack
int push(char c)
{
top++;
str[top]=c;
return 0;
}

int pop()
{
int val;
val=str[top];
top--;
return(val);
}
Infix to Postfix Conversion
(Priority for the operator)

int priority (char c)


{
if (c=='/'|| c=='*' || c=='%')
return 1;
else if(c=='+' || c=='-')
return 0;
}
?
Thank you.

Vous aimerez peut-être aussi