백준 10828번 스택

< 백준 10828번 스택 - 마포 코딩박 >

사용한 알고리즘: 구현


 문제에서 정의된 명령어를 구현하는 문제였습니다.

문제풀이는 다음과 같습니다.
(1) (코드 10~42)
 문제에서 정의된 명령어를 구현하는 함수를 하나 만듭니다.

(2) (코드 46~52)
 각 입력들을 과정(1)에서 만든 함수에 넣어 구현합니다.
 push가 아닌 입력들은 해당 값을 출력을 해줍니다.

#include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<int> st;
string a;
int N;
int func(string x){
if( x.compare("push") == 0){
int y;
cin >> y;
st.push(y);
return -500;
}
if( x.compare("pop") == 0){
if(st.empty())
return -1;
else{
int aa;
aa = st.top();
st.pop();
return aa;
}
}
if( x.compare("size") == 0)
return st.size();
if( x.compare("empty") == 0){
if(st.empty())
return 1;
else
return 0;
}
if(x.compare("top") == 0){
if(st.empty())
return -1;
else
return st.top();
}
}
int main(){ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);
cin >> N;
for (int i = 0; i < N; ++i){
cin >> a;
int now = func(a);
// push 입력이면 -500 출력
if(now != -500)
cout << now << '\n';
}
return 0;
}
view raw BOJ 10828.cpp hosted with ❤ by GitHub


댓글