Thursday, 23 November 2017

Postfix to Infix Expression

Postfix to infix conversion using Stack



Conversion of a Postfix Expression into an Infix Expression

We can use the following steps...

Step 1: Read the postfix expression from left to right .

Step 2: If the symbol is an operand, then push it onto the stack.

Step 3: If the symbol is an operator,

pop two symbols from the stack and create it as a string by placing the operator in between the operands and push the resulted string back to stack.

Step 4: Repeat steps 2 and 3 till the end of the postfix expression.

Step 5: EXIT


Example

Consider the following Postfix Expression...

A B - C D * +

The above postfix expression can be converted into infix expression using Stack data Structure as follows...

The equivalent infix Expression is as follows...

( ( A - B ) + ( C * D ) )


C program to convert postfix to infix expression

# include <stdio.h>
# include <conio.h>
# include <string.h>
# define MAX 100
void pop (char*);
void push(char*);
char stack[MAX] [MAX];
int top = -1;
int main()
{
  char s[MAX], str1[MAX], str2[MAX], str[MAX];
  char s1[2],temp[2];
  int i=0;

  printf("\Enter the postfix expression; ");
  gets(s);
  while (s[i]!='\0')
  {
     if(s[i] == ' ' ) /*skip whitespace, if any*/
     i++;

     if (s[i] == '^' || s[i] == '*'|| s[i] == '-' || s[i] == '+' || s[i] == '/')
     {
       pop(str1);
       pop(str2);
       temp[0] ='(';
       temp[1] ='\0';
       strcpy(str, temp);
       strcat(str, str2);
       temp[0] = s[i];
       temp[1] = '\0';
       strcat(str,temp);
       strcat(str, str1);
       temp[0] =')';
       temp[1] ='\0';
       strcat(str,temp);
       push(str);
     }
    
      else
     {
       temp[0]=s[i];
       temp[1]='\0';
       strcpy(s1, temp);
       push(s1);
     }
      i++;
  }
  printf("\nThe Infix expression is: %s", stack[0]);
}

void pop(char *a1)
{
  strcpy(a1,stack[top]);
  top--;
}

void push (char*str)
{
   if(top == MAX - 1)
   printf("\nstack is full");
 else
 {
    top++;
    strcpy(stack[top], str);
 }
}



Share this

1 Response to "Postfix to Infix Expression"

  1. Slots - Dr.MCD
    Free Slots Games and 인천광역 출장안마 No Download needed & No Registration 아산 출장안마 needed! Play free slots games 당진 출장안마 for fun at Dr.MCD! 강원도 출장마사지 Forgot Password? We Have 1 Problem? 경상남도 출장마사지

    ReplyDelete