【问题标题】:Operators not inserting in the stack in C while trying to convert an infix expression to a postfix one尝试将中缀表达式转换为后缀表达式时未在 C 中插入堆栈的运算符
【发布时间】:2020-04-08 15:38:32
【问题描述】:

我正在尝试实现 中缀到后缀 转换程序。在执行代码时,我只能看到字母数字字符。算术运算符不打印。调试后,我发现运算符没有插入堆栈。我找不到这背后的原因。

感谢任何帮助。

#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;
}

【问题讨论】:

    标签: c stack postfix-notation infix-notation


    【解决方案1】:

    正如您在调试会话中正确检测到的那样,您在 postfix 表达式中看不到运算符,因为您从未将它们 push() 到您的堆栈中。

    事实上

    • 在第一个 if 中检查字母数字字符
    • 在下面的else if 中检查左括号
    • 在第二个else if 中检查右括号
    • 在决赛中你从堆栈管理pops...但你没有推送任何东西(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
    

    输出:

    4 6 * 3 +
    

    (为了提高输出的可读性,我在printfs 中的每个%c 后面添加了一个空格)。


    注意:您仍然需要解决运营商优先级管理中的一些问题。

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 2013-11-12
      • 1970-01-01
      相关资源
      最近更新 更多