Postfix
Postfix
#include<stdio.h>
#include<ctype.h>
char S[50],Q[50];
int top=-1,front=-1,rear=-1;
void ENQUEUE(char item)
{
if(rear==49)
printf("Queue is full");
else if(front==-1)
{
front=0;rear=0;
Q[rear]=item;
}
else
{
rear=rear+1;
Q[rear]=item;
}
}
void Display()
{
if(front==-1)
printf("Queue is empty");
else
for(int i=front;i<=rear;i++)
printf("%c ",Q[i]);
}
void PUSH(char item)
{
if(top!=49)
S[++top]=item;
}
char POP()
{
return S[top--];
}
int isOperator(char c)
{
return(c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
}
int precedence(char c)
{
if(c=='+'||c=='-')
return 1;
if(c=='*'||c=='/')
return 2;
if(c=='^')
return 3;
}
void convert(char A[])
{
int i=0;
char ch;
while(A[i]!='\0')
{
ch=A[i];
if(isalnum(ch))
{
ENQUEUE(ch);
}
else if(ch=='(')
PUSH(ch);
else if(ch==')')
{
while(S[top]!='(')
ENQUEUE(POP());
POP();
}
else if(isOperator(ch))
{
if(S[top]=='('||top==-1)
PUSH(ch);
else
{
while(precedence(S[top])>=precedence(ch))
{
ENQUEUE(POP());
if(S[top]=='('||top==-1)
break;
}
PUSH(ch);
}
}
i++;
}
while(top!=-1)
ENQUEUE(POP());
}
void main()
{
char A[50];
printf("Enter Infix Expression\n");
scanf("%s",A);
convert(A);
Display();
}
OUTPUT
Enter Infix Expression
3-6*(7-1)
3 6 7 1 - * -
PROGRAM
#include<stdio.h>
#include<ctype.h>
int S[50],top=-1;
int POP()
{
return S[top--];
}
int isOperator(char c)
{
return(c=='+'||c=='-'||c=='*'||c=='/');
}
}
else if(isOperator(ch))
{
op2=POP();
op1=POP();
PUSH(operate(op1,ch,op2));
}
i++;
}
return POP();
}
void main()
{
char A[50];
printf("Enter Postfix Expression\n");
gets(A);
printf("%d",evaluate(A));
OUTPUT