SMALL
안녕하세요 오늘은 스택(stack) 자료구조를 이용한 문제를 풀어보겠습니다.
stl container에는 stack을 구현할 필요없이 이미 있기 때문에 편하게 풀 수 있습니다.
전략:
1. stack를 선언해주고(stack<int> s), for문을 이용하여 string타입으로 변수 x를 N번 입력을 받아줍니다.
2. 입력받은 x의 문자를 비교하여 push인지, pop인지, top인지 등등확인해줍니다. s.size()가 0이면 -1을 출력해야하는 것에 주의해야합니다.
코드:
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int N;
cin>>N;
stack<int> s;
for(int i= 0; i<N; i++){
string x;
cin>>x;
if(x=="push"){
int num;
cin>>num;
s.push(num);
}
else if(x=="top"){
if(s.size()==0){
cout<<"-1"<<"\n";
continue;
}
else cout<<s.top()<<"\n";
}
else if(x=="empty"){
cout<<s.empty()<<"\n";
}
else if(x=="pop"){
if(s.size()==0){
cout<<"-1"<<"\n";
}
else{
cout<<s.top()<<"\n";
s.pop();
}
}
else if(x=="size") cout<<s.size()<<"\n";
}
}
LIST
'BOJ 문제풀이' 카테고리의 다른 글
백준 9184번 c++ 풀이 (0) | 2021.08.06 |
---|---|
백준 10816번 c++ 풀이 (0) | 2021.08.06 |
백준 10866번 c++ 풀이 (0) | 2021.08.06 |
백준 2164번 c++ 풀이 (0) | 2021.08.06 |
백준 10845번 c++ 풀이 (0) | 2021.08.06 |