c - 中缀到后缀 C 程序

标签 c data-structures stack

我一直在制作一个程序,借助堆栈将中缀输入转换为后缀。
我编写的程序如下

这作为无限循环运行,不打印任何相关内容。我一直试图找到错误但没有成功,编译器也没有发出任何警告。

#include<stdio.h>

char po[20];
int top = -1;

void push(char x) {
  po[++top] = x;
}

char pop() {
  if (top == -1)
    return -1;
  else
    return po[top--];
}

int priority(char x) {
  if (x == '(')
    return 0;
  if (x == '+' || x == '-')
    return 1;
  if (x == '*' || x == '/')
    return 2;
}

main() {
  char st[20], x;
  int a, c = 0, op;
  printf("Enter the expression ");
  scanf("%s", st);
  while (st[c] != '\0') {
    if (st[c] >= 'a' && st[c] <= 'z')
      printf("%c", st[c]);
    else if (st[c] == '(')
      push(st[c]);
    else if (st[c] == ')')
      ;
    {
      while ((x = pop()) != '(')
        printf("%c", pop());
    }
    if (st[c] == '*' || st[c] == '/' || st[c] == '+' || st[c] == '-'
        || st[c] == '^') {
      while (priority(po[top]) >= priority(st[c]))
        printf("%c", pop());
      push(st[c]);
    }
    c = c + 1
  }
  while (top != -1) {
    printf("%c", pop());
  }
}

最佳答案

The compiler also did not issue any warnings.

节省时间。启用所有警告或获取更好的编译器。

warning: control reaches end of non-void function [-Wreturn-type]

查看下面的函数,发现它没有为所有可能的 x 返回值。

int priority(char x) {
  if (x == '(')
    return 0;
  if (x == '+' || x == '-')
    return 1;
  if (x == '*' || x == '/')
    return 2;

  // Missing return
}
<小时/>
warning: suggest braces around empty body in an 'if' statement [-Wempty-body]

下面的代码是可疑的。您真的想要在 else if (st[c] == ')') 之后添加 ; 吗?

else if (st[c] == ')')
  ;
<小时/>
error: expected ';' before '}' token

肯定是拼写错误(缺少;)

// c = c + 1
c = c + 1;
<小时/>

也可能存在其他问题。

关于c - 中缀到后缀 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54368416/

相关文章:

c - 如何将actionscript代码转换为c代码?

c++ - 在堆栈的自定义实现中重载 == 运算符

java - 这个递归阶乘函数中的乘法何时完成?

c - 批处理文件在编译C程序时换行

c - 如何分配客户端连接的主机名和端口号?

c++ - 如何从动态库中调用未知函数?

algorithm - 如何将一棵树与大量模式进行匹配?

将一棵二叉树复制到另一棵二叉树的C程序

java - 关于Java中选择合适的数据结构的问题

c++ - c++中队列的反转