自己联系 栈

自己联系  栈 王道P79 简单 
#include <iostream>
#include <cstdio>
#include <stack>
#include <string>

using namespace std;

int main(){
    int n;
    char str;
    while(cin>>n){
        stack<int> mystack;
//        stack<char> mystack;
        while(!mystack.empty())  mystack.pop();
        for(int i=0;i<n;i++){
//            getline(cin,str);
            cin>>str;
            if(str == 'A'){
                if(mystack.empty()){
                    cout<<'E'<<endl;
                } else{
                    cout<<mystack.top()<<endl;
                }
            }else if(str == 'O'){
                if(!mystack.empty()) mystack.pop();
            }else{
//                mystack.push(str.substr(2) - '0'); //todo 语法error
//                mystack.push(str.substr(2));
                int m;
                cin>>m;
                mystack.push(m);
            }

        }
        printf("\n");

    }
    return 0;
}



书本上的例题
//栈的应用  -- 表达式求值 P78
//https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130?tpId=63&tqId=29576&tPage=1&ru=/kaoyan/retest/9001&qru=/ta/zju-kaoyan/question-ranking
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>

using namespace std;

int Priority(char c){
    if(c == '#') return 0;
    else if(c =='$')  return 1;
    else if(c =='+' || c =='-')  return 2;
    else return 3;
}

double GetNumber(string str,int& index){
    double number = 0;
    while(isdigit(str[index])){
        number = number * 10 + str[index] - '0';
        index++;
    }
    return number;
}

double Calculate(double x,double y,char op){
    double result = 0;
    if(op == '+'){
        result = x+y;
    }else if(op == '-'){
        result = x - y;
    }else if(op == '*'){
        result = x * y;
    }else if(op == '/'){
        result = x / y;
    }
    return result;
}

int main(){
    string str;
    while(getline(cin,str)){
//        if(str == '0'){ // error  要用双引号
        if(str == "0"){ //
            break;
        }
        int index = 0;
        stack<char> oper; //运算符栈
        stack<double> data;// 运算数栈
        str += '$';
        oper.push('#');
        while(index < str.size()){
            if(str[index] == ' '){
                index++;
            }else if(isdigit(str[index])){
                data.push(GetNumber(str,index));
            }else{
                if(Priority(oper.top()) < Priority(str[index])){
                    oper.push(str[index]);
                    index++;
                }else{
                    double y = data.top();
                    data.pop();
                    double x = data.top();
                    data.pop();
                    data.push(Calculate(x,y,oper.top()));
                    oper.pop();
                }



            }
        }
        printf("%.2f\n",data.top());
    }

    return 0;
}

最后改为
cout<<data.top();
就是习题5.2的解




全部评论

相关推荐

11-20 15:03
四川大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务