다음을 처리하는 프로그램을 작성하시오
스택을 활용하여 문제를 풀었습니다.
스택을 이용하여 해당되는 명령어에 맞게 실행시켜 주었습니다.
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
void init() {
ios_base::sync_with_stdio(false);
cin.tie(0);
}
int main() {
init();
// 초기 스택을 초기화 시켜준다.
stack<int> s;
// 명령어와 push가 들어왔을 때의 숫자를 입력 받을 num 변수
string fun;
int num;
int j=0;
int ans[10000];
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> fun;
if (fun == "push") { // push 명령어
cin >> num;
s.push(num);
}
if (fun == "top") {
if (s.size() == 0)
ans[j++] = -1;
else
ans[j++] = s.top();
}
if (fun == "pop") { // pop 명령어
if (s.size() == 0)
ans[j++] = -1;
else {
ans[j++] = s.top();
s.pop();
}
}
if (fun == "size") { // size 명령어
ans[j++] = s.size();
}
if (fun == "empty") { // empty 명령어
if (s.empty())
ans[j++] = 1;
else
ans[j++] = 0;
}
}
for (int i = 0; i < j; i++) { // 출력
cout << ans[i] << endl;
}
return 0;
}