用C语言栈写一个后缀表达式计算
时间: 2023-12-20 08:04:58 浏览: 93
下面是用C语言栈实现后缀表达式计算的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct stack {
int top;
int capacity;
int *array;
} Stack;
Stack *createStack(int capacity) {
Stack *stack = (Stack*) malloc(sizeof(Stack));
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
return stack;
}
int isFull(Stack *stack) {
return stack->top == stack->capacity - 1;
}
int isEmpty(Stack *stack) {
return stack->top == -1;
}
void push(Stack *stack, int item) {
if (isFull(stack)) {
printf("Stack is full\n");
return;
}
stack->array[++stack->top] = item;
}
int pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->array[stack->top--];
}
int peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->array[stack->top];
}
int evaluatePostfix(char *exp) {
Stack *stack = createStack(100);
int i, operand1, operand2, result;
for (i = 0; exp[i] != '\0'; ++i) {
if (isdigit(exp[i])) {
push(stack, exp[i] - '0');
} else {
operand2 = pop(stack);
operand1 = pop(stack);
switch (exp[i]) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
printf("Invalid operator\n");
return -1;
}
push(stack, result);
}
}
return pop(stack);
}
int main() {
char exp[] = "231*+9-";
int result = evaluatePostfix(exp);
printf("Result: %d\n", result);
return 0;
}
```
这个程序的核心在于`evaluatePostfix`函数,它使用了一个栈来计算后缀表达式。具体流程是遍历后缀表达式,如果遇到数字则将其压入栈中,如果遇到运算符则从栈中弹出两个操作数进行计算,并将结果压回栈中。最终栈中只剩下一个元素,即为后缀表达式的计算结果。
阅读全文