给我一个C++计算后缀表达式的代码
时间: 2023-12-20 15:05:40 浏览: 73
以下是使用栈实现的C语言计算后缀表达式的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_EXPRESSION_LEN 100
typedef struct stack {
int top;
int* array;
} Stack;
Stack* createStack(int capacity) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
stack->array = (int*)malloc(capacity * sizeof(int));
return stack;
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
void push(Stack* stack, int item) {
stack->array[++stack->top] = item;
}
int pop(Stack* stack) {
if (isEmpty(stack)) {
return -1;
}
return stack->array[stack->top--];
}
int evaluatePostfix(char* expression) {
Stack* stack = createStack(strlen(expression));
int i, num1, num2, result;
for (i = 0; expression[i]; i++) {
if (isdigit(expression[i])) {
push(stack, expression[i] - '0');
} else {
num1 = pop(stack);
num2 = pop(stack);
switch (expression[i]) {
case '+':
push(stack, num2 + num1);
break;
case '-':
push(stack, num2 - num1);
break;
case '*':
push(stack, num2 * num1);
break;
case '/':
push(stack, num2 / num1);
break;
}
}
}
result = pop(stack);
free(stack);
return result;
}
int main() {
char expression[MAX_EXPRESSION_LEN];
printf("Enter a postfix expression: ");
fgets(expression, MAX_EXPRESSION_LEN, stdin);
printf("Result: %d\n", evaluatePostfix(expression));
return 0;
}
```
注意:这个代码只能计算不带括号的后缀表达式,如果要计算带括号的后缀表达式,需要修改代码。
阅读全文