[英]Operators not inserting in the stack in C while trying to convert an infix expression to a postfix one
I am trying to implement an infix-to-postfix conversion program.我正在尝试实现一个中缀到后缀的转换程序。 On executing the code I get to see only alpha-numeric characters.
在执行代码时,我只能看到字母数字字符。 Arithmetic operators are not printing.
算术运算符不打印。 Upon debugging, I found the operators are not inserting in the stack.
调试后,我发现运算符没有插入堆栈。 I couldn't find out the reason behind this.
我找不到这背后的原因。
Any help is appreciated.任何帮助表示赞赏。
#include<stdio.h>
#include <ctype.h>
#define MAX 50
char st[MAX];
int top = -1;
void push(char);
char pop();
int priority(char);
int main()
{
int i=0;
char x,s[50];
printf("Enter infix expression: ");
gets(s);
while(s[i]!='\0')
{
if(isalnum(s[i]))
printf("%c",s[i]);
else if(s[i] == '(')
push(s[i]);
else if(s[i] == ')')
{
while((x=pop())!='(')
printf("%c",x);
}
else
{
while(priority(st[top])>=priority(s[i]))
printf("%c",pop());
push(st[i]);
}
i++;
}
while(top!=-1)
printf("%c",pop());
}
void push(char x)
{
st[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return (st[top--]);
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/' || x == '%')
return 2;
}
As you correctly detected on your debugging session, you don't see operators in your postfix expression because you never push()
them to your stack.正如您在调试 session 时正确检测到的那样,您在后缀表达式中看不到运算符,因为您从未将它们
push()
到堆栈中。
In fact实际上
if
you check for alphanumeric charactersif
您检查字母数字字符else if
you check for opening parenthesis else if
中else if
you check for closing parenthesis else if
您检查右括号,则在第二个中pop
s from stack... but you didn't push anything !pop
......但你没有推送任何东西! (1) What you need to fix is the last else
, where you have at least two distinct problems:您需要解决的是最后一个
else
,您至少有两个明显的问题:
st[top]
without checking top
value.st[top]
而不检查top
值。 You need to manage the case in which top = -1
, that would lead to out of bounds access of the stack array and to undefined behavior.top = -1
的情况,这将导致堆栈数组的越界访问和未定义的行为。 I think that in that scenario you just need to push the operatorst[i]
.st[i]
。 Probably you meant s[i]
s[i]
In this way the while analysing the expression becomes这样,while 分析表达式就变成了
while(s[i]!='\0')
{
if(isalnum(s[i]))
printf("%c ",s[i]);
else if(s[i] == '(' )
push(s[i]);
else if(s[i] == ')')
{
while((x=pop())!='(')
printf("%c ",x);
}
else
{
if( top != -1 )
{
while(priority(st[top])>=priority(s[i]))
printf("%c ",pop());
}
push(s[i]);
}
i++;
}
Input:输入:
4*6+3
Output: Output:
4 6 * 3 +
(I added a further space after each %c
in printf
s in order to improve output readability). (为了提高 output 的可读性,我在
printf
中的每个%c
之后添加了一个空格)。
Note : You still have to fix some problems in operators priority management.注意:您仍然需要解决运营商优先级管理中的一些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.