题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

#include <cmath>
#include <iostream>
#include <string>
using namespace std;

void top(int *st, int* &st_top){
    if (st == st_top) {
        cout<<"error"<<endl;
    }else {
        cout<<*st_top<<endl;
    } 
}

void push(int * st, int* &st_top, int num){
    st_top++;
    *st_top=num;
}

void pop(int *st, int* &st_top){
    if (st != st_top) {
        top(st, st_top);
        st_top--;
    }else {
        cout<<"error"<<endl;
    }
}


int main() {
    int n, i=0;
    int st[100000];
    int *st_top = st;
    string s;int num;
    cin >> n;
    getline(cin, s);
    while (i<n) {
        getline(cin, s);
        // cout<<s<<endl;
        num = 0;
        int pos = s.find(' ');
        if(pos==4){
            
            int k=s.substr(5,s.size()).size();
            
            for(auto x: s.substr(5,s.size())){
                num = num + (int)(x -'0')*pow(10, k-1);
                k--;
                // cout<<(int)(x -'0')<<" "<<num<<endl;
            }
            
            push(st, st_top, num);
        }else {
            if (s=="pop") {
                pop(st, st_top);
            }else {
                top(st, st_top);
            }
        }
        // cout<<s<<" "<<pos<<endl;
        i++;
    }

}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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