C语言前缀表达式转后缀
时间: 2023-09-11 11:06:57 浏览: 138
将前缀表达式从右往左遍历,遇到操作数就直接输出到后缀表达式中,遇到运算符则将其压入栈中,等到遇到下一个操作数时,将栈顶运算符取出与该操作数和前面的运算符进行运算,将结果输出到后缀表达式中。最后将栈中的所有运算符依次弹出并输出到后缀表达式中即可。
以下是 C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK_SIZE 100
typedef struct stack {
char data[MAX_STACK_SIZE];
int top;
} Stack;
void push(Stack *s, char c) {
if (s->top == MAX_STACK_SIZE - 1) {
printf("Stack overflow!\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top--];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
void prefix_to_postfix(char *prefix, char *postfix) {
Stack stack;
stack.top = -1;
int len = strlen(prefix);
for (int i = len - 1; i >= 0; i--) {
if (is_operator(prefix[i])) {
char op1 = pop(&stack);
char op2 = pop(&stack);
postfix[strlen(postfix)] = op1;
postfix[strlen(postfix)] = op2;
postfix[strlen(postfix)] = prefix[i];
push(&stack, postfix[strlen(postfix) - 1]);
} else {
push(&stack, prefix[i]);
}
}
while (stack.top != -1) {
postfix[strlen(postfix)] = pop(&stack);
}
postfix[strlen(postfix)] = '\0';
}
int main() {
char prefix[100], postfix[100] = "";
printf("Enter prefix expression: ");
gets(prefix);
prefix_to_postfix(prefix, postfix);
printf("Postfix expression: %s", postfix);
return 0;
}
```
阅读全文
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.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)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)