本题实现了用二叉树实现后缀表达式转换为中缀表达式,代码封装效果很好。
输入要求:
- 要求运算符和数字之间以空间间隔开来
- 最后可以有
=
也可以没有
输出的中缀表达式都每一部分都含有括号
这是可以进行优化的点
//
// Created by 86152 on 2023/6/9.
//
//Author hugo
//Time 2023/6/9 11:36
/*
*本题是表达式计算的题目,需要将后缀表达式转化为中缀表达式
* 需要输入的数字和运算符之间以空格分开
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
#define NUMBER 1
#define OPERATOR 2
typedef struct aNode {
int state;
int num;
char op;
struct aNode *leftchild;
struct aNode *rightchild;
} Node;
typedef struct aStack {
Node *stack[MAX_SIZE];
int top;
} Stack;
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '/' || ch == '*');
}
Node *initList(char *string) {
if (isOperator(string[0])) {
Node *node = (Node *) malloc(sizeof(Node));
node->state = OPERATOR;
node->op = string[0];
node->leftchild = NULL;
node->rightchild = NULL;
return node;
} else {
int N = atoi(string);
Node *node = (Node *) malloc(sizeof(Node));
node->state = NUMBER;
node->num = N;
node->leftchild = NULL;
node->rightchild = NULL;
return node;
}
}
Stack *initStack() {
Stack *S = (Stack *) malloc(sizeof(Stack));
S->top = -1;
for (int i = 0; i < MAX_SIZE; ++i) {
S->stack[i] = NULL;
}
return S;
}
int isEmpty(Stack *S) {
return (S->top == -1);
}
int isFull(Stack *S) {
return S->top == MAX_SIZE;
}
Node *popStack(Stack *S) {
if (isEmpty(S)) {
printf("The stack is empty\n");
exit(1);
}
return S->stack[(S->top)--];
}
void pushStack(Stack *S, Node *data) {
if (isFull(S)) {
printf("The stack is full\n");
exit(1);
}
S->stack[++(S->top)] = data;
}
void VISIT(Node *node) {
if (node->state == NUMBER) {
printf("%d", node->num);
} else {
printf("%c", node->op);
}
}
Node *bulidTree() {
Stack *S = initStack();
char str[20];
while (scanf("%s", str) != EOF) {
Node *node = initList(str);
if (str[0] == '=') break;
if (node->state == OPERATOR) {
Node *p = popStack(S);
Node *q = popStack(S);
node->leftchild = q;
node->rightchild = p;
pushStack(S, node);
} else {
pushStack(S, node);
}
}
return S->stack[0];
}
void inorderTraversal(Node *root) {
if (root == NULL) return;
if (root->leftchild != NULL || root->rightchild != NULL) {
printf("(");
}
inorderTraversal(root->leftchild);
VISIT(root);
inorderTraversal(root->rightchild);
if (root->leftchild != NULL || root->rightchild != NULL) {
printf(")");
}
}
int main() {
char postfix[MAX_SIZE];
printf("input the postfix : \n");
Node *root = bulidTree();
inorderTraversal(root);
return 0;
}