![](/img/trans.png)
[英]Infix to Postfix using stack in C <incorrect output after a '(' is inserted in the expression>
[英]Operators not inserting in the stack in C while trying to convert an infix expression to a postfix one
我正在嘗試實現一個中綴到后綴的轉換程序。 在執行代碼時,我只能看到字母數字字符。 算術運算符不打印。 調試后,我發現運算符沒有插入堆棧。 我找不到這背后的原因。
任何幫助表示贊賞。
#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;
}
正如您在調試 session 時正確檢測到的那樣,您在后綴表達式中看不到運算符,因為您從未將它們push()
到堆棧中。
實際上
if
您檢查字母數字字符else if
中else if
您檢查右括號,則在第二個中pop
......但你沒有推送任何東西! (1) 您需要解決的是最后一個else
,您至少有兩個明顯的問題:
st[top]
而不檢查top
值。 您需要管理top = -1
的情況,這將導致堆棧數組的越界訪問和未定義的行為。 我認為在那種情況下你只需要推動運營商st[i]
。 可能你的意思是s[i]
這樣,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++;
}
輸入:
4*6+3
Output:
4 6 * 3 +
(為了提高 output 的可讀性,我在printf
中的每個%c
之后添加了一個空格)。
注意:您仍然需要解決運營商優先級管理中的一些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.