Infix To Postfix Super Easy C program Using Stack library.


#include<stdio.h>

#include "sss.h"



int priority(char ch)

{

   if(ch == '(')

      return 0;

   if(ch == '+' || ch == '-')

      return 1;

   if(ch =='*' || ch=='/')

      return 2;

}

int main()

{

    char exp[20];

    char ch,temp;

    printf("Enter Infix Expression:");

    scanf("%s",exp);

    STACK s;

    s.top=-1;



    int i;

     for(i=0;exp[i]!='\0';i++)

     {

         ch=exp[i];

         if(isalnum(ch))

            printf("%c",ch);

         else if(ch == '(')

         push(&s,ch);

        else if(ch == ')')

        {

            while((ch=pop(&s))!= '(')

                    printf("%c",ch);

        }

        else

        {

            while(priority(peek(&s)) >= priority(ch))

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

            push(&s,ch);

        }

     }

     while(!isempty(&s))

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

}


 


Output:

Enter Infix Expression: (A+B)*C

AB+C*

Process returned 0 (0x0)   execution time : 12.129 s

Press any key to continue.




Stack Library:


#define MAXSIZE 20
typedef struct stack
{
char data[MAXSIZE];
int top;
}STACK;
int isempty(STACK *ps)
{
return ps->top==-1;
}
int isfull(STACK *ps)
{
return ps->top==MAXSIZE-1;
}
void push(STACK *ps, char num)
{
ps->data[++ps->top]=num;
}
int pop(STACK *ps)
{
char num;
num=ps->data[ps->top];
ps->top--;
return num;
//return ps->data[ps->top--];
}
int peek(STACK *ps)
{
return ps->data[ps->top];
}

Post a Comment

0 Comments