Conversion from Postfix to Infix

Application of Stacks

Conversion from Postfix to Infix

The algorithm for converting a Postfix expression to Infix notation is as follows:

  •  Accept a postfix string from the user.
  • Start scanning the string from left to right one character at a time.
  • If it is an operand, push it in stack.
  • If it is an operator, pop opnd2, opnd1 and concatenate them in the order (opnd1, optr, opnd2) as follows:

strcpy(arr,opnd1);
strcat(arr,optr);
stract(arr,opnd2);

Push the result in the stack.

  • Repeat these steps until arr of input postfix string ends.
  • Pop the remaining element of the stack, which is the required Infix notation equivalent to a given Postfix notation.


Program to convert a Postfix expression to Infix:

#include <stdio.h>

#include <conio.h>
#include <stdlib.h>

#define MAX 20

struct stack
{
int top;
char arr[MAX];
};

void push(struct stack *,char);
char pop(struct stack *);
int isdigit(char);
void postfix_to_infix(char instr[],char outstr[]);

void main()
{
char postfix[MAX],infix[MAX];
clrscr();
printf(“nEnter a postfix string?”);
gets(postfix);
printf(“nPostfix string is: %s”,postfix);
postfix_to_infix(postfix,infix);
printf(“nInfix string is: %s”,infix);
getch();
}

void push(struct stack *s,char ch)
{
if(s->top==MAX-1)
{printf(“Stack Overflow!”);
exit(1);
}
s->arr[++(s->top)]=ch;
}

char pop(struct stack *s)
{
if(s->top==-1)
{
printf(“Stack Underflow!”);
exit(1);
}
return(s->arr[(s->top)–]);
}

int isdigit(char ch)
{return(ch>=’0′ && ch<=’9′); }

void postfix_to_infix(char instr[],char outstr[])
{
int i,z=0,ct=1;
char ch,opnd1,opnd2;
struct stack stk;
stk.top=-1;
for(i=0;(ch=instr[i])!=’�’;i++)
{
if(isdigit(ch))
{push(&stk,ch); }
else {
if(ct==1)
{opnd2=pop(&stk);
opnd1=pop(&stk);
outstr[z++]=opnd1;
outstr[z++]=ch;
outstr[z++]=opnd2;
ct++;
}
else {opnd2=pop(&stk);
outstr[z++]=ch;
outstr[z++]=opnd2;
}
}
}
outstr[z]=’�’;
}