본문 바로가기
Programming/Algorithm

백준 스택

by OKOK 2018. 1. 29.

/*

오케이 이렇게 하나씩 풀어나가면 됩니다. 정수를 저장하는 스택을 구현한 다음,

입력으로 주어지는 명령을 처리하는 프로그램을 작성하세요.

푸시 팝, 사이즈 엠티, 탑 스택의 가장 위에 있는 정수를 출력하세요.

팝이랑 탑이랑 구분할 필요가 있ㅅ습니다.

첫째 줄에 주어지는 명령의 수가 주어집니다. 스택에 대해서 모르니 이것은 정답을 보고

풀어보도록 하겠습니다. 

*/


#include <iostream>

#include <stack>

#include <string>


using namespace std;


int main(void) {

int n;

cin >> n;


stack<int> st;

string str;


for (int i = 0; i < n; i++) {

cin >> str;

if (str == "push") {

int num;

cin >> num;

st.push(num);

}

else if (str == "pop") {

if (!st.empty()) {

cout << st.top() << endl;

st.pop();

}

else {

cout << "-1" << endl;

}

}

else if (str == "size") {

cout << st.size() << endl;

}

else if (str == "empty") {

if (st.empty()) {

cout << "1" << endl;

}

else {

cout << "0" << endl;

}

}

else if (str == "top") {

if (!st.empty()) {

cout << st.top() << endl;

}

else {

cout << "-1" << endl;

}

}

}

return 0;


백준 스택에 대해서 알아봅니다. 스택은 위에서 쌓고 위에서 뺴는 자료구조 입니다. 그러므로 여기서는 탑, 팝 이 있고 엠티, 사이즈, 푸시라는 명령어가 존재합니다. 오케이요. 이것들에 대해서 자유롭게 사용가능하면, 이것을 가지고, 구현을 하면 됩니다.