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



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

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  

某些操作意味着它从堆栈中弹出两次,插入"空格+运算符+空格",并用括号括起来。然后将其推入堆栈中。

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

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 = '') {
/* 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 != '') {
digits[i++] = *exp++;
}
digits[i] = '';
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] = '';
bwparens[0] = '(';
strcat(strcat(strcat(bwparens, pop1), temp), ")");
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 设置为始终等于空终止,这会导致无限循环:

while (*exp = '')

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

我希望这有所帮助。

最新更新