前缀后缀表达式求值c语言代码
时间: 2023-07-31 07:06:33 浏览: 124
以下是一个简单的前缀表达式求值的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK_SIZE 100
typedef struct stack {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack is full!\n");
return;
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
return s->data[s->top--];
}
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
return s->data[s->top];
}
int evaluatePrefix(char *exp) {
Stack *s = (Stack *) malloc(sizeof(Stack));
initStack(s);
int len = strlen(exp);
for (int i = len - 1; i >= 0; i--) {
if (exp[i] >= '0' && exp[i] <= '9') {
push(s, exp[i] - '0');
} else {
int op1 = pop(s);
int op2 = pop(s);
switch (exp[i]) {
case '+':
push(s, op1 + op2);
break;
case '-':
push(s, op1 - op2);
break;
case '*':
push(s, op1 * op2);
break;
case '/':
push(s, op1 / op2);
break;
default:
printf("Invalid operator!\n");
return -1;
}
}
}
int result = pop(s);
free(s);
return result;
}
int main() {
char *exp = "-+42*35";
printf("Prefix expression: %s\n", exp);
int result = evaluatePrefix(exp);
printf("Result: %d\n", result);
return 0;
}
```
注意,这里只实现了加、减、乘、除四种操作符。如果需要支持其他操作符,需要在 switch 语句中添加相应的分支。
相关推荐
![](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)
![](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)
![](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)