简单实现逆波兰表达式求值
isdigit(c)
:判断字符c
是否为数字(0-9
) ,是则返回非零值,否则返回 0 。例如'7'
传入返回非零,'x'
传入返回 0 。
#include <stdio.h>
#include <ctype.h>
#define SZ 100
// 用数组模拟栈
int stack[SZ], top = -1;
// 压栈
void push(int n) { stack[++top] = n; }
// 出栈
int pop() { return stack[top--]; }
int rpnEval(char* s) {
while (*s) {
if (isdigit(*s))
push(*s - '0');
else {
int b = pop(), a = pop();
switch (*s) {
case '+': push(a + b); break;
case '-': push(a - b); break;
case '*': push(a * b); break;
case '/': push(a / b); break;
}
}
s++;
}
return pop();
}
int main() {
char expr[SZ];
scanf("%s", expr);
printf("%d\n", rpnEval(expr));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 1000
// 定义栈的结构
typedef struct SqStack {
int data[MAX_SIZE];
int top;
} SqStack;
// 栈的初始化
void InitStack(SqStack* S) {
S->top = -1;
}
// 压栈
void Push(SqStack* S, int e) {
S->data[++(S->top)] = e;
}
// 出栈
int Pop(SqStack* S) {
return S->data[(S->top)--];
}
// 逆波兰表达式求值
int rpnEvaluate(char* expr) {
SqStack stack;
InitStack(&stack);
char* token = expr;
while (*token != '\0') {
if (isdigit(*token)) {
int num = 0;
while (isdigit(*token)) {
num = num * 10 + (*token - '0');
token++;
}
Push(&stack, num);
token--;
} else if (isspace(*token)) {
token++;
continue;
} else {
int op2 = Pop(&stack);
int op1 = Pop(&stack);
switch (*token) {
case '+':
Push(&stack, op1 + op2);
break;
case '-':
Push(&stack, op1 - op2);
break;
case '*':
Push(&stack, op1 * op2);
break;
case '/':
Push(&stack, op1 / op2);
break;
}
token++;
}
token++;
}
return Pop(&stack);
}
int main() {
char expr[MAX_SIZE];
scanf("%s", expr);
int result = rpnEvaluate(expr);
printf("%d\n", result);
return 0;
}