用白色空格中缀到postfix

时间:2014-11-20 17:53:11

标签: c data-structures

我有一个将中缀表单转换为后缀表单的程序。 例如,输入为:(-2+4-(3+3)) 那么输出是:2-4+33+- 我预期的输出是:2 - 4 + 3 3 + - 我应该怎么做才能改变它,当我弹出()堆栈时,我正在想更多的空间。 这是代码:

#include <stdio.h>
#include <ctype.h>
#include<string.h>

#define SIZE 50

char s[SIZE];
int top = -1;

void push(char elem) {
  s[++top] = elem;
}

char pop() {
  return (s[top--]);
}

int pr(char elem) {
  switch (elem) {
    case '#':
      return 0;
    case '(':
      return 1;
    case '+':
    case '-':
      return 2;
    case '*':
    case '/':
      return 3;
  }
}

int main()
{
  char infx[50], pofx[50], ch, elem;
  int i = 0, k = 0;
  printf("\n\nRead the Infix Expression ?");
  scanf("%s", infx);
  push('#');
  while ((ch = infx[i++]) != '\0') {
    if (ch=='(')
      push(ch);
    else if (isalnum(ch))
      pofx[k++] = ch;
    else if (ch == ')') {
      while (s[top] != '(')
        pofx[k++] = pop();
      elem = pop();
    } else {
      while (pr(s[top]) >= pr(ch))
        pofx[k++] = pop();
      push(ch);
    }
  }
  while (s[top] != '#')
    pofx[k++] = pop();
  pofx[k] = '\0';
  printf("\n\nGiven Infix Expn: %s Postfix Expn: %s \n", infx,pofx);
}

谢谢

1 个答案:

答案 0 :(得分:0)

首先,由于这行

,我无法编译您的代码
int top = -1;

void push(char elem) {
s[++top] = elem;
}

使用负数变量初始化数组非常危险。当我们转到pop()数组中的字符符号时,它将返回到top = -1处的初始状态,这会导致编译错误。我的建议是将你的代码更改为类似的东西,这将导致你在数组中放置字符来改变一些事情:

int top = 0;

void push(char elem) {
    s[top++] = elem;
}

至于打印字符串,每个字符之间都有空格,请使用以下内容:

for (int i = 0, i < stren(infix) + 1; i++)
{
    printf ("%c ", infix[i]);
}

// Same goes for the postfix. More of a formatting of the print characters really...