繁体   English   中英

尝试将中缀表达式转换为后缀表达式时,运算符未插入 C 的堆栈中

[英]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您检查右括号,则在第二个中
  • 在最后 else 你从堆栈管理pop ......但你没有推送任何东西 (1)

您需要解决的是最后一个else ,您至少有两个明显的问题:

  1. 您访问st[top]而不检查top值。 您需要管理top = -1的情况,这将导致堆栈数组的越界访问和未定义的行为。 我认为在那种情况下你只需要推动运营商
  2. 你推入堆栈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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM