[Acwing]828. 模拟栈 原创

算法标签 栈

题目简叙

在这里插入图片描述

思路

push

	stk[++tt]=tmpN; 

pop

	tt--;

query

	cout<<stk[tt]<<endl;

empty

	if(tt>0)cout<<"NO";
	else cout<<"YES";

代码

数组模拟

#include<iostream>
#include<string.h>

using namespace std;
const int N = 100000+10;
int stk[N],tt;

int main(){
    int m;
    cin>>m;
    
    string op;
    int tmpN;
    while(m--){
        cin>>op;
        if(op=="push"){
            cin>>tmpN;
            stk[++tt]=tmpN;
        }
        else if(op=="query"){
            cout<<stk[tt]<<endl;
        }
        else if(op=="pop"){
            tt--;
        }
        else if(op=="empty"){
            if(tt>0)cout<<"NO";
            else cout<<"YES";
            cout<<endl;
        }
    }
        
    return 0;
}

在这里插入图片描述
STL栈

#include<iostream>
#include<stack>

using namespace std;

stack<int>stk;

int main(){
    int n;
    cin>>n;
    string op;
    int tmpN;
    while(n--){
        cin>>op;
        if(op=="query"){
            cout<<stk.top()<<endl;
        }
        else if(op=="push"){
            cin>>tmpN;
            stk.push(tmpN);
        }
        else if(op=="pop"){
            stk.pop();
        }
        else if(op=="empty"){
            if(stk.empty())cout<<"YES"<<endl;
            else cout<<"NO"<<endl;
        }
    }
    return 0;
}

在这里插入图片描述

posted @ 2024-02-04 14:52  俺叫西西弗斯  阅读(0)  评论(0)    收藏  举报  来源