2133-数据结构实验之栈与队列三:后缀式求值

来源:互联网 发布:怎么检查网络被盗用 编辑:程序博客网 时间:2024/05/19 09:14
#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;}
阅读全文
0 0
原创粉丝点击