任务描述
本关任务:从键盘上输入一个后缀表达式,试编写算法计算表达式的值。规定:逆波兰表达式的长度不超过一行,以$符作为输入结束,操作数之间用空格分隔,操作符只可能有+、−、∗、/
四种运算。例如:234 34+2*$。
测试说明
测试输入:234 34+2*$ 预期输出:536
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//顺序栈定义
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100//顺序栈存储空间的初始分配量
typedef int Status;
typedef double SElemType;
typedef struct {
SElemType *base;//栈底指针
SElemType *top;//栈顶指针
int stacksize;//栈可用的最大容量
} SqStack;
//算法3.1 顺序栈的初始化
Status InitStack(SqStack &S) {
//构造一个空栈S
S.base = new SElemType[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
if (!S.base)
exit(OVERFLOW); //存储分配失败
S.top = S.base; //top初始为base,空栈
S.stacksize = MAXSIZE; //stacksize置为栈的最大容量MAXSIZE
return OK;
}
//算法3.2 顺序栈的入栈
Status Push(SqStack &S, SElemType e) {
// 插入元素e为新的栈顶元素
if (S.top - S.base == S.stacksize)
return ERROR; //栈满
*(S.top++) = e; //元素e压入栈顶,栈顶指针加1
return OK;
}
//算法3.3 顺序栈的出栈
Status Pop(SqStack &S, SElemType &e) {
//删除S的栈顶元素,用e返回其值
if (S.base == S.top)
return ERROR;//栈空
e = *(--S.top); //栈顶指针减1,将栈顶元素赋给e
return OK;
}
//算法3.4 取顺序栈的栈顶元素
double GetTop(SqStack S) {//返回S的栈顶元素,不修改栈顶指针
if (S.top != S.base) //栈非空
return *(S.top - 1); //返回栈顶元素的值,栈顶指针不变
}
double Postfix() {
//###### Begin ######
SqStack S;
InitStack(S);
char t[100] ;
fgets(t,1024,stdin);
int i = 0;
while (t[i] != '$') {
if (t[i] >= '0' && t[i] <= '9') {
SElemType x = 0;
while (t[i] >= '0' && t[i] <= '9') {
x = x * 10 + t[i] - '0';
i++;
}
Push(S, x);
} else if (t[i] == ' ') {
i++;
} else {
SElemType a, b, c;
Pop(S, a);
Pop(S, b);
if (t[i] == '+') {
c = b + a;
} else if (t[i] == '-') {
c = b - a;
} else if (t[i] == '*') {
c = b * a;
} else if (t[i] == '/') {
c = b / a;
}
Push(S, c);
i++;
}
}
return *(S.base);
// ###### End ######
}
int main() {
double x;
x = Postfix();
cout << x;
}