帮我用C语言写一个能将算术运算表达式转换为逆波兰式的函数
时间: 2024-05-05 19:18:27 浏览: 128
逆波兰式计算,将格式化数组转化为逆波兰表达式,a为输入的数组,n为其长度,p为输出逆波兰表达式的目标
好的,关于您的问题,我可以回答。以下是一种将中缀表达式转换为逆波兰式的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 50
typedef struct stack {
char items[SIZE];
int top;
} stack;
void push(stack* s, char c) {
if (s->top < SIZE - 1) {
s->items[++(s->top)] = c;
}
}
char pop(stack* s) {
if (s->top >= 0) {
return s->items[(s->top)--];
}
return -1;
}
int is_digit(char c) {
return (c >= '0' && c <= '9');
}
int is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int precedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
char* infix_to_postfix(char* expression, int n) {
stack* s = (stack*) malloc(sizeof(stack));
s->top = -1;
char* postfix = (char*) malloc(n + 1);
int i, j = 0;
for (i = 0; i < n; i++) {
if (is_digit(expression[i])) {
postfix[j++] = expression[i];
} else if (is_operator(expression[i])) {
while (s->top >= 0 &&
阅读全文