机试指南第五章 数据结构一

P79 习题5.1

http://t.cn/AiKKM6F6
在这里插入图片描述

#include <iostream>
#include <stack>

using namespace std;

int main(){
    freopen("D://case.txt","r",stdin);
    int n;
    while(cin>>n){
        char operate;
        int temp;
        stack <int> sta;
        for (int i=0;i<n;i++){
            cin>>operate;
            if (operate == 'P'){
                cin>>temp;
                sta.push(temp);
            }
            if (operate == 'O'){
                if (!sta.empty()){
                    sta.pop();
                }
            }
            if (operate == 'A'){
                if (sta.empty()){cout<<'E'<<endl;}
                else {cout<<sta.top()<<endl;}
            }
        };
        cout<<endl;
    }
    return 0;
}

P79 习题5.2

http://t.cn/AiKKJ5
在这里插入图片描述

#include <iostream>
#include <string>
#include <stack>

using namespace std;

double getnum(int &i,string str){
    int num = 0;
    for (;i<str.size();i++){
        if (isdigit(str[i])){
            num = num*10+str[i]-'0';
        }
        else{break;}
    }
    return num;
}

int prior(char x){
    if (x == '#'){return 0;}
    if (x == '$'){return 1;}
    if (x == '+'||x == '-'){return 2;}
    if (x == '*'||x == '/'){return 3;}
}

double  calculate(double  x,double  y,char operate){
    //cout<<x<<operate<<y<<endl;
    if (operate == '+'){return x+y;}
    if (operate == '-'){return x-y;}
    if (operate == '*'){return x*y;}
    if (operate == '/'){return x/y;}
}

int main(){
    freopen("D:\\case.txt","r",stdin);
    stack <char> operate;
    stack <double> num;
    string stringcase;
    cin>>stringcase;
    operate.push('#');
    stringcase += "$";
    int i=0;
    while(i<stringcase.size()){
        if (isdigit(stringcase[i])){
            num.push(getnum(i,stringcase));
        }
        else{
            if (prior(stringcase[i])>prior(operate.top())){
                operate.push(stringcase[i++]);
            }
            else {
                double  x,y;
                y = num.top();
                num.pop();
                x = num.top();
                num.pop();
                num.push(calculate(x,y,operate.top()));
                operate.pop();
            }
        }
    }
    cout<<num.top();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值