Data Structure

# Infix to Postfix Conversion

### Procedure for Postfix Conversion

 1 Scan the Infix string from left to right. 2 Initialize an empty stack. 3 If the scanned character is an operand, add it to the Postfix string. 4 If the scanned character is an operator and if the stack is empty push the character to stack. 5 If the scanned character is an Operator and the stack is not empty, compare the precedence of the character with the element on top of the stack. 6 If top Stack has higher precedence over the scanned character pop the stack else push the scanned character to stack. Repeat this step until the stack is not empty and top Stack has precedence over the character. 7 Repeat 4 and 5 steps till all the characters are scanned. 8 After all characters are scanned, we have to add any character that the stack may have to the Postfix string. 9 If stack is not empty add top Stack to Postfix string and Pop the stack. 10 Repeat this step as long as stack is not empty.

### Algorithm for Postfix Conversion

```S:stack
while(more tokens)
x<=next token
if(x == operand)
print x
else
while(precedence(x)<=precedence(top(s)))
print(pop(s))
push(s,x)
while(! empty (s))
print(pop(s))
```

### Conversion To Postfix

EXAMPLE:
`A+(B*C-(D/E-F)*G)*H`
StackInputOutput
Empty A+(B*C-(D/E-F)*G)*H-
Empty +(B*C-(D/E-F)*G)*HA
+ (B*C-(D/E-F)*G)*HA
+( B*C-(D/E-F)*G)*HA
+( *C-(D/E-F)*G)*HAB
+(* C-(D/E-F)*G)*HAB
+(* -(D/E-F)*G)*HABC
+(- (D/E-F)*G)*HABC*
+(-( D/E-F)*G)*HABC*
+(-( /E-F)*G)*HABC*D
+(-(/ E-F)*G)*HABC*D
+(-(/ -F)*G)*HABC*DE
+(-(- F)*G)*HABC*DE/
+(-(- F)*G)*HABC*DE/
+(-(- )*G)*HABC*DE/F
+(- *G)*HABC*DE/F-
+(-* G)*HABC*DE/F-
+(-* )*HABC*DE/F-G
+ *HABC*DE/F-G*-
+* HABC*DE/F-G*-
+*EndABC*DE/F-G*-H
EmptyEndABC*DE/F-G*-H*+

### Infix to postfix implementation in c

```#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
push(char elem)
{
s[++top]=elem;
}

char pop()
{
return(s[top--]);
}

int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
}

void main()
{
char infx[50],pofx[50],ch,elem;
int i=0,k=0;
clrscr();
printf("\n\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(') push(ch);
else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop();
}
else
{
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#')
pofx[k++]=pop();
pofx[k]='\0';
printf("\n\nGiven Infix Expn: %s  Postfix Expn: %s\n",infx,pofx);
getch();
}
```