1. 程式人生 > >2133-資料結構實驗之棧與佇列三:字尾式求值

2133-資料結構實驗之棧與佇列三:字尾式求值

#include <bits/stdc++.h>

using namespace std;
typedef int ElemType;

class Stack{
private:
    ElemType *up;
    ElemType *base;
    ElemType length;
public:
    Stack();
    void push(ElemType);
    void pop();
    ElemType top(){return *(up - 1);}
    ElemType size(){return length;}
    bool
empty(){return 0 == length;} }; ElemType cal(ElemType a, ElemType b, char op); int main() { char st[1123]; while(cin >> st) { Stack Q; for(int i = 0; st[i]; i++) { if(st[i] == '#') { break; } if
(isdigit(st[i])) { Q.push(st[i] - '0'); } else{ int a = Q.top(); Q.pop(); int b = Q.top(); Q.pop(); int x = cal( b, a, st[i]); Q.push(x); } } cout
<< Q.top() << endl; } return 0; } Stack::Stack(){ base = new ElemType; up = base; length = 0; } void Stack::push(ElemType x){ *up++ = x; length++; } void Stack::pop(){ up--; length--; } ElemType cal(ElemType a, ElemType b, char op){ if(op == '+') return a + b; if(op == '-') return a - b; if(op == '*') return a * b; if(op == '/') return a / b; return 0; }