这是我写的代码。我没有得到正确的输出,有时我在操作数之间得到随机符号。我哪里出错了?
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define size 20
struct postfix //Postfix Expression Stack
{
char post[size];
int posttop;
};
struct symbol //Symbol Stack
{
char sym[size];
int symtop;
};
int priority(char ch) //Checks the priority of Operatoes
{
switch(ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
}
void push_post(struct postfix *s, char c) //pushes character to postfix stack
{
s->posttop++;
s->post[s->posttop]=c;
}
void push_sym(struct symbol *s, char c) //pushes character to postfix expression stack
{
s->symtop++;
s->sym[s->symtop]=c;
}
char pop(struct symbol *s)
{
return(s->sym[(s->symtop)--]); //returns the popped character
}
void show( struct postfix p)
{
int i;
for(i=0;i<=p.posttop;i++)
printf("%c",p.post[i]);
}
void main()
{
struct postfix p;
struct symbol s;
p.posttop=-1;
s.symtop=-1;
char ch;
char exp[20];
int i;
printf("Enter your infix expression : ");
gets(exp);
int l=strlen(exp);
for(i=0;i<=l;i++)
{
if (isalpha(exp[i])){
push_post(&p,exp[i]);
}
else if(exp[i]=='(')
push_sym(&s,exp[i]);
else if (exp[i]==')')
{
while(s.sym[s.symtop]!='(')
{
ch = pop(&s);
push_post(&p,ch);
}
ch=pop(&s); //pop the opening bracket and do nothing
}
else
{
while(priority(s.sym[s.symtop])<=priority(exp[i])) //while priority of top operator of stack is less than the read operator
{
ch=pop(&s); // Pop the top operator of symbol stack
push_post(&p,ch); //push the operator popped from symbol stack to prefix stack
}
push_sym(&s,exp[i]); //push the read symbol
}
}
while(s.symtop!=-1)
{
ch=pop(&s);
push_post(&p, ch);
}
printf("Postfix Expression : ");
show(p);
getch();
}
导致此错误的原因是什么?它适用于像a+b+c
等小型表达式。但是我的大型表达式和大括号都会出错。