-
[백준/10828] 스택자료구조 2021. 1. 14. 23:51728x90
1. STL 활용
#include <iostream> #include <string> #include <stack> using namespace std; int N; stack<int> s; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin>>N; for(int i=0;i<N;i++){ string cmd; cin>>cmd; if( cmd.compare("push") == 0 ) { int input; cin>>input; s.push(input); }else if( cmd.compare("top") == 0 ){ if( s.empty() ) cout<<"-1\n"; else cout<<s.top()<<"\n"; }else if( cmd.compare("size") == 0){ cout<<s.size()<<"\n"; }else if( cmd.compare("empty") == 0){ cout<<s.empty()<<"\n"; }else if( cmd.compare("pop") == 0 ){ if( s.empty() ) cout<<"-1\n"; else{ int top = s.top(); s.pop(); cout<<top<<"\n"; } } } return 0; }
2. Non STL
#include <iostream> #include <string> using namespace std; int N; struct stack{ int sp; int arr[10001]; void init(){ sp=0; for(int i=0;i<=10000;i++) arr[i]=0; } void push(int data){ arr[sp++]=data; } int pop(){ return sp==0?-1:arr[--sp]; } int top(){ return sp==0?-1:arr[sp-1]; } int size(){ return sp; } bool empty(){ return sp==0; } }; stack s; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin>>N; for(int i=0;i<N;i++){ string cmd; cin>>cmd; if( cmd.compare("push")==0 ){ int data; cin>>data; s.push(data); }else if(cmd.compare("pop")==0){ cout<<s.pop()<<"\n"; }else if(cmd.compare("size")==0){ cout<<s.size()<<"\n"; }else if(cmd.compare("empty")==0){ cout<<s.empty()<<"\n"; }else if(cmd.compare("top")==0){ cout<<s.top()<<"\n"; } } return 0; }
728x90'자료구조' 카테고리의 다른 글
[백준/7785] 회사에 있는 사람 (0) 2021.01.18 [백준/1620] 나는야 포켓몬 마스터 이다솜 (0) 2021.01.18 [백준/5397] 키로거 (0) 2021.01.17 [백준/10866] 덱 (0) 2021.01.16 [백준/10845] 큐 (0) 2021.01.15