Search This Blog

Loading...

Conversion of an expression from Postfix into Infix and Prefix

/*Conversion of an expression from postfix into infix
  Conversion of an expression from postfix into prefix
*/
#include<ctype.h>
#include<stdio.h>
#include<conio.h>
#define MAX 20
#include<string.h>

void convert_prefix(char x);
void convert_infix(char x);
char stack[MAX][MAX];
void postfix_to_prefix(char postfix[],char prefix[]);
void postfix_to_infix(char postfix[],char prefix[]);
int top;

/* array sstack[][] is being used  as a stck of strings */

void main()
{
    char postfix[30],infix[30],prefix[30];
    clrscr();
    printf("\nEnter a postfix expression :");
    gets(postfix);
    postfix_to_prefix(postfix,prefix);
    printf("\nPrefix :    %s",prefix);
    postfix_to_infix(postfix,infix);
    printf("\nInfix :     %s",infix);
    getch();
}

   void postfix_to_prefix(char postfix[],char prefix[])
     {
       char x,st1[20];
       int i;
       top=-1;
       for(i=0;postfix[i]!='\0';i++)//scan the infix expression from
         {                          //left to right.
          x=postfix[i];
          if(isalnum(x))
            {
            /* convert character x  to string format */
            st1[0]=x;
            st1[1]='\0';
            // push the operand on the stack s2
            top=top+1;
            strcpy(stack[top],st1);
             }
        else  // if operator ,convert to prefix
             {
              convert_prefix(x);
             }
          }
    //Result is on top of the stack
    strcpy(prefix,stack[top]);
}

void postfix_to_infix(char postfix[],char infix[])
     {
       char x,st1[20];
       int i;
       top=-1;
       for(i=0;postfix[i]!='\0';i++)//scan postfix expression from
         {                          //left to right
          x=postfix[i];
          if(isalnum(x))
             {
            /* convert token to string form */
            st1[0]=x;
            st1[1]='\0';
            // push the operand on the stack s2
            top=top+1;
            strcpy(stack[top],st1);
              }
          else // if operator, convert to infix
             convert_infix(x);

          }
    //Result is on top of the stack
    strcpy(infix,stack[top]);
}


void convert_prefix(char x)
{       char st1[30];
    st1[0]=x;
    st1[1]='\0';
    strcat(st1,stack[top-1]);
    strcat(st1,stack[top]);
    top=top-1;
    strcpy(stack[top],st1);
}
void convert_infix(char x)
{       char st1[30],st2[10];
    st1[0]='(';
    st1[1]='\0';
    strcat(st1,stack[top-1]);
    st2[0]=x;
    st2[1]='\0';
    strcat(st1,st2);
    strcat(st1,stack[top]);
    st2[0]=')';
    st2[1]='\0';
    strcat(st1,st2);
    top=top-1;
    strcpy(stack[top],st1);
}

No comments:

Post a Comment