#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#include "string.h"
typedef struct {
char data[100];
int top; // 栈顶指针
}SqStack;
void convert(char* arr, int strlen, char* res);
int main() {
char arr[100];
char res[100];
scanf("%s", arr);
convert(arr, strlen(arr), res);
printf("%s", res);
return 0;
}
void convert(char* arr, int strlen, char* res) {
// 创建栈
SqStack sqStack = {{}, -1};
int index = 0;
for (int i = 0; i < strlen; ++i) {
// 若是数字直接加入res数组
if ('0' <= arr[i] && '9' >= arr[i]) {
// 注意数字可能有多位
while ('0' <= arr[i] && '9' >= arr[i]) {
//printf("%c\n", arr[i]);
res[index++] = arr[i++];
}
i--;
} else if (arr[i] != ')') {
// 运算符入栈
sqStack.data[++sqStack.top] = arr[i];
} else {
// 碰见右括号栈内运符出栈
while (sqStack.data[sqStack.top] != '(') {
//printf("%c\n", sqStack.data[sqStack.top]);
res[index++] = sqStack.data[sqStack.top--];
}
sqStack.top--;
}
}
// 栈中若有剩余则全部出栈
while (sqStack.top > -1) {
res[index++] = sqStack.data[sqStack.top--];
}
res[index] = '\0';
}
利用栈实现中缀表达式转化为后缀表达式
最新推荐文章于 2024-07-24 21:24:38 发布