用栈实现逆波兰表达式C++代码
时间: 2023-04-07 22:03:13 浏览: 110
cpp代码-栈的应用-逆波兰表达式
以下是用栈实现逆波兰表达式的C代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void push(Stack *s, int value) {
if (s->top == MAX_STACK_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int main() {
Stack s;
s.top = -1;
char c;
int num1, num2;
while ((c = getchar()) != '\n') {
if (isdigit(c)) {
push(&s, c - '0');
} else {
num2 = pop(&s);
num1 = pop(&s);
switch (c) {
case '+':
push(&s, num1 + num2);
break;
case '-':
push(&s, num1 - num2);
break;
case '*':
push(&s, num1 * num2);
break;
case '/':
push(&s, num1 / num2);
break;
default:
printf("Invalid operator\n");
exit(1);
}
}
}
printf("%d\n", pop(&s));
return 0;
}
阅读全文