C语言栈实现表达式计算
时间: 2024-05-04 19:12:53 浏览: 16
C语言中可以使用栈来实现表达式计算。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义栈结构
typedef struct {
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 isEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFull(Stack* stack) {
return stack->top == stack->capacity - 1;
}
// 入栈
void push(Stack* stack, int item) {
if (isFull(stack)) {
printf("栈已满,无法入栈\n");
return; }
stack->array[++stack->top] = item;
}
// 出栈
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("栈为空,无法出栈\n");
return -1;
}
return stack->array[stack->top--];
}
// 获取栈顶元素
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("栈为空\n");
return -1;
}
return stack->array[stack->top];
}
// 表达式计算函数
int evaluateExpression(char* expression) {
Stack* stack = createStack(strlen(expression));
int i, operand1, operand2, result;
for (i = 0; expression[i] != '#'; i++) {
if (expression[i] >= '0' && expression[i] <= '9') {
push(stack, expression[i] - '0');
} else {
operand2 = pop(stack);
operand1 = pop(stack);
switch (expression[i]) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
printf("无效的运算符\n");
return -1;
}
push(stack, result);
}
}
return pop(stack);
}
int main() {
char expression[100];
printf("请输入表达式(以#结尾):");
scanf("%s", expression);
int result = evaluateExpression(expression);
printf("计算结果:%d\n", result);
return 0;
}
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)