[C++]백준10828번 스택

less than 1 minute read

오늘은 백준10828번 스택 문제를 풀어보도록 하자. 기본적인 함수를 이용하여 푸는 문제이다. 간단하다.

문제는 다음과 같다.

                               [접근법]

  1. 그냥 따라서 한다.
                                     [코드]
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int N,M;
	string txt;
	stack<int>s;

	cin >> N;
	
	while (N--) {
		cin >> txt;

		if (txt == "push") {
			cin >> M;
			s.push(M);
		}
		else if (txt == "pop") {
			if (!s.size()) {
				cout << -1 << '\n';
			}
			else {
				cout << s.top() << '\n';
				s.pop();
			}
		}
		else if (txt == "size"){
			cout << s.size() << '\n';
		}
		else if (txt == "empty") {
			if (s.size()) {
				cout << 0 << '\n';
			}
			else {
				cout << 1 << '\n';
			}
		}
		else if (txt == "top") {
			if (s.size()) {
				cout << s.top() << '\n';
			}
			else {
				cout << -1 << '\n';
			}
		}
	}
	return 0;
}