c语言栈实现四则运算
时间: 2023-07-28 08:06:29 浏览: 101
栈实现四则运算
实现一个栈来进行四则运算,首先需要定义栈的数据结构。栈是一种后进先出的数据结构,可以使用数组或链表来实现。这里我们使用数组来实现。
```
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void init(Stack *s)
{
s->top = -1;
}
int is_empty(Stack *s)
{
return s->top == -1;
}
int is_full(Stack *s)
{
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack *s, int x)
{
if (is_full(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s)
{
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int peek(Stack *s)
{
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top];
}
```
接下来,我们可以使用这个栈来实现四则运算。我们假设输入的表达式中只包含加减乘除和数字,没有括号和负数。
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_EXPR_SIZE 100
int evaluate(char *expr)
{
Stack operand;
Stack operator;
init(&operand);
init(&operator);
while (*expr != '\0') {
if (isdigit(*expr)) {
int num = 0;
while (isdigit(*expr)) {
num = num * 10 + (*expr - '0');
expr++;
}
push(&operand, num);
} else if (*expr == '+' || *expr == '-' || *expr == '*' || *expr == '/') {
while (!is_empty(&operator) && peek(&operator) != '(' && ((*expr == '+' || *expr == '-') ? peek(&operator) != '*' && peek(&operator) != '/' : 1)) {
int op = pop(&operator);
int b = pop(&operand);
int a = pop(&operand);
switch (op) {
case '+':
push(&operand, a + b);
break;
case '-':
push(&operand, a - b);
break;
case '*':
push(&operand, a * b);
break;
case '/':
push(&operand, a / b);
break;
}
}
push(&operator, *expr);
expr++;
} else if (*expr == '(') {
push(&operator, *expr);
expr++;
} else if (*expr == ')') {
while (peek(&operator) != '(') {
int op = pop(&operator);
int b = pop(&operand);
int a = pop(&operand);
switch (op) {
case '+':
push(&operand, a + b);
break;
case '-':
push(&operand, a - b);
break;
case '*':
push(&operand, a * b);
break;
case '/':
push(&operand, a / b);
break;
}
}
pop(&operator);
expr++;
} else {
printf("Invalid character: %c\n", *expr);
exit(1);
}
}
while (!is_empty(&operator)) {
int op = pop(&operator);
int b = pop(&operand);
int a = pop(&operand);
switch (op) {
case '+':
push(&operand, a + b);
break;
case '-':
push(&operand, a - b);
break;
case '*':
push(&operand, a * b);
break;
case '/':
push(&operand, a / b);
break;
}
}
int result = pop(&operand);
if (!is_empty(&operand)) {
printf("Invalid expression\n");
exit(1);
}
return result;
}
int main()
{
char expr[MAX_EXPR_SIZE];
printf("Enter an expression: ");
fgets(expr, MAX_EXPR_SIZE, stdin);
int result = evaluate(expr);
printf("Result: %d\n", result);
return 0;
}
```
这个程序可以处理如下的表达式:
```
3+4*5-6/2
(3+4)*5/(2+3)
```
阅读全文