后缀表达式转中缀表达式c语言
时间: 2023-08-09 18:06:05 浏览: 466
后缀表达式转中缀表达式需要使用栈来实现。
具体步骤如下:
1. 从左到右遍历后缀表达式的每个元素。
2. 如果当前元素为操作数,则将其压入栈中。
3. 如果当前元素为操作符,则弹出栈顶的两个元素作为操作数,将其与操作符组成中缀表达式,然后将中缀表达式压入栈中。
4. 最终栈中只剩下一个中缀表达式,即为转换后的中缀表达式。
下面是一个示例代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct node {
char *data;
struct node *next;
} Node;
typedef struct stack {
Node *top;
} Stack;
void push(Stack *s, char *data) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = s->top;
s->top = new_node;
}
char *pop(Stack *s) {
if (s->top == NULL) {
return NULL;
}
char *data = s->top->data;
Node *tmp = s->top;
s->top = s->top->next;
free(tmp);
return data;
}
int is_operator(char *data) {
return strcmp(data, "+") == 0 || strcmp(data, "-") == 0 ||
strcmp(data, "*") == 0 || strcmp(data, "/") == 0;
}
char *to_infix(char **postfix, int len) {
Stack s;
s.top = NULL;
for (int i = 0; i < len; i++) {
if (isdigit(postfix[i][0])) {
push(&s, postfix[i]);
} else if (is_operator(postfix[i])) {
char *op1 = pop(&s);
char *op2 = pop(&s);
char *expr = (char *)malloc(strlen(op1) + strlen(op2) + strlen(postfix[i]) + 3);
sprintf(expr, "(%s %s %s)", op2, postfix[i], op1);
push(&s, expr);
free(op1);
free(op2);
}
}
return pop(&s);
}
int main() {
char *postfix[] = {"3", "4", "5", "*", "+"};
char *infix = to_infix(postfix, 5);
printf("%s\n", infix);
free(infix);
return 0;
}
```
在上述代码中,我们定义了两个结构体:`Node`表示栈节点,`Stack`表示栈。`push`和`pop`分别用于入栈和出栈操作。`is_operator`用于判断一个字符串是否为操作符。`to_infix`函数实现了后缀表达式转中缀表达式的核心算法。最后,我们使用一个示例后缀表达式计算其中缀表达式并输出。
注意:这里的实现只适用于不带括号的后缀表达式。如果后缀表达式中有括号,需要进行更复杂的处理。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)