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 = '\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')
我认为这可能是问题之一。
我希望这个对你有用。
推荐阅读
- django - 如何使用 Django Rest Framework 和 Django 在视图中预处理上传的图像
- django - 为什么 Django 更新页面和注销不起作用?
- r - 在R中扩展(缓冲)形状文件的边界
- android - Compose with Hilt last version (2.35) 问题:找不到方法
- arrays - 使用 jq 为每个值在空间上拆分 JSON 数组字符串
- javascript - 如何在 javscript 中获取 img 标签的 currentSrc?
- angular - 通过 Angular/TypeScript 中的 HTTP-Get-Request 循环使用不同的值
- java - 为什么我收到此错误 FormatException (FormatException: Invalid double null)
- html - 我可以通过缓存动态加载 Web 组件引用的数据吗?
- merge - 合并两个表的脚本