Subscribe Us

Responsive Advertisement

Advertisement

problem 26(infix to postfix) using stack

 problem 26(infix to postfix) using stack




//problem 26(infix to postfix)

#include<stdio.h>

int stack[100];

int top=-1;

void push(char x)

{

    top++;

    stack[top]=x;

}

char pop()

{

    if(top==-1)return -1;

    char c;

    c=stack[top];

    top--;

    return c;

}

int priority(char x)

{

    if(x=='(')return 0;

    if(x=='+'||x=='-')return 1;

    if(x=='*'||x=='/')return 2;

    if(x=='^')return 3;

}

int main()

{

    int i=0;

    char exp[50];

    char ch;

    printf("Enter your expession : ");

    scanf("%s",exp);

    while(1)

    {

       if(exp[i]=='\0')break;

       if(isalnum(exp[i]))

       {

           printf("%c",exp[i]);

       }

       else if(exp[i]=='(')

       {

           push(exp[i]);

       }

      else if(exp[i]==')')

      {

          while(1)

          {

              char c;

              c=pop();

              if(c=='(')break;

              printf("%c",c);

          }

      }

     else

     {

         while(priority(stack[top])>=priority(exp[i]))

         {

             printf("%c",pop());

         }

         push(exp[i]);

     }

     i++;

    }

  while(top!=-1)

  {

      printf("%c",pop());


  }

    return 0;

}


Post a Comment

0 Comments