使用数组堆栈将后缀转换为中缀表示法

标签 c arrays postfix-notation infix-notation

我正在尝试编写一个将后缀转换为中缀表示法的程序,但这对我来说并不容易。

pfix  stack          explanation (@ is space)  
---------------------------------------------  
3     3  
4     3 4  
5     3 4 5  
+     3 (4@+@5)      if exp[i] is op, do some action  
*     (3@*@(4@+@5))  if exp[i] is op, do some action  

某些 Action 意味着从堆栈中弹出两次,插入“空格+运算符+空格”,并用括号括起来。然后将其压入堆栈。

但是当我执行这个程序时,它根本不起作用。

cygwin_exception::open_stackdumpfile:将堆栈跟踪转储到 post2in.exe.stackdump

我该如何解决这个问题?

谢谢。

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

#define M 20
#define N 20

char stk[M][N];  // array of string
int top = -1;

void push(char (*)[N], char *);
char *pop(char (*)[N]);
void getexp(char *);
int isop(char);

int main() {
  char *exp = "abc+*";
  getexp(exp);
  printf("%s ", *stk[0]);
  return 0;
}

void getexp(char *exp) {
  while (*exp = '\0') {

    /* if space or tab, skip */
    if (*exp == ' ' || *exp == '\t') exp++;

    /* if digit or point, get whole number and store it into array stack */
    else if (isdigit(*exp) || *exp == '.') {
      char digits[20];
      int i = 0;
      while (*exp != ' ' && *exp != '\0') {
        digits[i++] = *exp++;
      }
      digits[i] = '\0';
      push(stk, digits);
    }

    /* if operator, pop twice and wrap them with parenthesis with operator */
    else if (isop(*exp)) {
      char bwparens[20], pop1[20], pop2[20], temp[4];
      strcpy(pop2, pop(stk));
      strcpy(pop1, pop(stk));
      temp[0] = ' ';
      temp[1] = *exp;
      temp[2] = ' ';
      temp[3] = '\0';
      bwparens[0] = '(';
      strcat(strcat(strcat(bwparens, pop1), temp), ")\0");
      push(stk, bwparens);
      exp++;
    }
  }
}

int isop(char chr) {
  return (chr == '+' || chr == '-' || chr == '*' || chr == '/' || chr == '%');
}

void push(char stk[M][N], char *exp) {
  if (top == -1) {
    printf("Stack is full");
    exit(EXIT_FAILURE);
  } else
    strcpy(stk[++top], exp);
}

char *pop(char stk[M][N]) {
  if (top == -1) {
    printf("Stack is empty.\n");
    exit(EXIT_FAILURE);
  } else {
    return stk[top--];
  }
}

最佳答案

您将 exp 设置为始终等于 null 终止,这会导致无限循环:

while (*exp = '\0')

我认为这可能是问题之一。

我希望这会有所帮助。

关于使用数组堆栈将后缀转换为中缀表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539816/

相关文章:

c - 如何在C中逐行读取由制表符分隔的双数据组成的10 GB txt文件

javascript - 使用 D3 在 JSON 中嵌套数组

c++ - RPN短路评估

C++后缀评估问题

c - 后缀计算器不起作用,为什么? - C

c - 函数的意外输出

c - MPI有超时机制吗?

C编程: Protected memory across fork()

java - 编程挑战扫雷帮助 : How to check for a "*" in a 2D string array?

Javascript,检索数组名称