#include<iostream>
#include<ctype.h>
#define size 50
using namespace std;
char s[size];
int top=-1;
push(char elem)
{
s[++top]=elem;
}
char pop()
{
return (s[top--]);
}
int pr(char elem)
{
switch(elem)
{
case '=':return 0;
case '(':return 1;
case '-':
case '+':return 2;
case '*':
case '/':return 3;
}
}
int main()
{
char infix[50],postfix[50],ch,elem;
int i=0,k=0;
cout<<"read the infix expression:";
cin>>infix;
push('=');
while((ch=infix[i++])!='\0')
{
if(ch=='(') push(ch);
else
if(isalpha(ch)) postfix[k++]=ch;
else
if(ch==')')
{
while(s[top]!='(')
postfix[k++]=pop();
elem=pop();
}
else
{
while(pr(s[top])>=pr(ch))
postfix[k++]=pop();
push(ch);
}
}
while(s[top]!='=')
postfix[k++]=pop();
postfix[k]='\0';
cout<<endl<<"postfix expression:"<<postfix;
return 0;
}
0 comments:
Post a Comment