我正在尝试使用堆栈将中缀表示法转换为后缀表示法。我编写了以下代码,但它给了我错误:
/Users/apple/Desktop/infix.c|49|error: expected expression
我无法找到错误。请帮助我更正此代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100
char st[MAX];
int top = -1;
void push(char st[],char);
char pop(char st[]);
void InfixtoPostfix(char source[],char target[]);
int getPriority(char);
int main(){
char infix[100],postfix[100];
printf("enter any infix expression");
fflush(stdin);
gets(infix);
strcpy(postfix,"");
InfixtoPostfix(infix,postfix);
printf("\nthe corresponding postfix expression is:");
puts(postfix);
return 0;
}
void InfixtoPostfix(char source[],char target[]){
int i=0,j=0;
char temp;
strcpy(target,"");
while(source[i]!='\0')
{
if(source[i]=='(')
{
push(st,source[i]);
i++;
}
else if(source[i]==')')
{
while((top!=-1)&&(st[top]!='('))
{
target[j]=pop(st);
j++;
}
if(top==-1)
{
printf("\nincorrect syntax");
exit(1);
}
temp=pop(st);
i++;
else if((isdigit(source[i]))||(isalpha(source[i]))
{
target[j]=source[i];
j++;
i++;
}
else if(source[i]=='+'||source[i]=='- '||source[i]=='*'||source[i]='/'||source[i]=='%d')
{
while((top!=-1)&&(st[top]!='(')&&(getPriority(st[top])>getPriority(source[i])))
{
target[j]=target[i];
i++;
}
push(st,source[i]);
i++;
}
else{
printf("\nincorrect expression");
exit(1);
}
}
while((top!=-1)&&(st[top]!='('))
{
target[j]=pop(st);
j++;
}
target[j]='\0';
}
}
int getPriority(char op)
{
if(op=='/'||op=='*'||op=='%'||op=='%')
return 1;
else if(op=='+'||op=='-')
return 0;
}
void push(char st[],char val)
{
if(top==MAX-1)
printf("overflow");
else{
top++;
st[top]=val;
}
}
char pop(char st[])
{
char val=' ';
if(top==-1)
printf("underflow");
else{
val=st[top];
top--;
}
return val;
}
最佳答案
问题很多,其中最重要的是
else if((isdigit(source[i]))||(isalpha(source[i]))
缺少右括号,您的编码风格很难被注意到
else if ((isdigit(source[i]) != 0) || (isalpha(source[i]) != 0))
并且不要使用 gets()
它已被弃用,在您的情况下
fgets(infix, sizeof(infix), stdin);
可以工作,并且有防止缓冲区溢出的好处。
关于c - 使用堆栈将中缀表示法转换为后缀表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174911/