[YM]模板-栈

概念:

“先进后出”,只有一个出入口

编程中的递归就是用栈来实现的

通常使用STL中的stack或者手写栈

 

成员函数:

empty()         //堆栈为空则返回真

pop()            //移除栈顶元素

push()           //在栈顶增加元素

size()            //返回栈中元素数目

top()              //返回栈顶元素

clear()            //清空栈内元素

先上模板

模板:

struct Stack{
    int data[N]={0},len=0;
    void pop(){
        len--;
    }
    void push(int e){
        data[++len]=e;
    }
    int top(){
        return data[len];
    }
    bool empty(){
        return len==0;
    }
    int size(){
        return len;
    }
    void clear(){
        len=0;
    }
};

这里就不用vector写了

毕竟STL库中有stack,几乎不用手写

这里就是供初学者学习

模板题:

洛谷:B3614 【模板】栈 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

代码:

/*---code---*/
const int N = 1e6 + 5;
using ull=unsigned long long;
struct Stack{
    ull data[N]={0},len=0;
    void pop(){
        len--;
    }
    void push(ull e){
        data[++len]=e;
    }
    ull top(){
        return data[len];
    }
    bool empty(){
        return len==0;
    }
    ull size(){
        return len;
    }
    void clear(){
        len=0;
    }
};
Stack st;
int q;
void solve(){
    st.clear();
    cin>>q;
    while(q--){
        string op;ull x;
        cin>>op;
        if(op=="push")cin>>x,st.push(x);
        if(op=="query"){
            if(st.empty())cout<<"Anguei!\n";
            else cout<<st.top()<<"\n";
        }
        if(op=="pop"){
            if(st.empty())cout<<"Empty\n";
            else st.pop();
        }
        if(op=="size")cout<<st.size()<<"\n";
    }
}

/*---main---*/

int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    // freopen("a.txt","r",stdin);
    // freopen("cout.txt","w",stdout);
    int T = 1;
    cin >> T;
    while(T--)
        solve();
    return 0;
}

PAT:这里非常注意的是给的数据范围是0<x<2^64 这里就要使用unsigned long long

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值