使用数组堆栈将后缀转换为中缀符号

问题描述 投票:0回答:1

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

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  

[某些动作意味着它从堆栈中弹出两次,插入“ space + operator + space”,并用括号将其包装起来。然后将其推入堆栈。

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

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--];
  }
}
c arrays postfix-notation infix-notation
1个回答
1
投票

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

while (*exp = '\0')

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

我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.