我是一名试图学习数据结构的初学者程序员,但我目前在这个特定的代码中遇到问题,我花了很多时间,但仍然不知道问题所在。我用指针输入 stack 中的元素,我的教授直接使用像 infix[i] 这样的数组,我不知道我的方法是否错误,但我想尝试一些新的东西。
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>
#define max 100
char stack[max];
int top=-1;
char pop();
char push(char x);
int priority(char x);
void infixtopostfix(char *infix,char* postfix);
int main()
{
char infix[100],postfix[100];
printf("Enter the expression");
fgets(infix,max,stdin);
infixtopostfix(infix,postfix);
puts(postfix);
}
char pop ()
{ char val;
if (top==-1)
{printf("underflow");
exit(1);
}
else
{
val=stack[top--];
return val;
}
}
char push(char x)
{
if(top==max-1)
{printf("overflow");
exit(1);}
else
{
stack[++top]=x;
}
}
int priority(char x )
{
if(x=='^')
return 3;
if(x=='*'||'/')
return 2;
if(x=='+'||'-')
return 1;
}
void infixtopostfix(char *infix,char* postfix)
{
char *p,*i;
i=infix;
p=postfix;
while(*i!='\0')
{
if(isalpha(*i)||isdigit(*i))
{
*p=*i;
p++;
i++;
}
else if(*i=='(')
{
push(*i);
i++;
}
else if(*i==')')
{
while((top!=-1)&&(stack[top]!='('))
{
*p=pop();
p++;
}
if(top==-1)
{
printf("invalid statement");
exit(1);
}
pop();
i++;
}
else if(*i=='+'||*i=='*'||*i=='/'||*i=='-'||*i=='^')
{
while((top!=-1)&&stack[top]!='(')
{if(priority(*i)<=priority(stack[top]))
{
*p=pop();
p++;
}
push(*i);
i++;}
}
else
{
printf("invalid expression");
exit(1);
}
}
while((top!=-1)&&(stack[top]!='('))
{
*p=pop();
p++;
}
*p='\0';
}
对于输入 (a+b),预期输出应该是 ab+ 但代码没有给出任何输出
代码至少存在以下问题:
节省时间,启用所有警告
warning: control reaches end of non-void function [-Wreturn-type]
缺少
priority()
的回报。