Baekjoon/Silver

C++ / 백준 / 10828 / 스택

GitHubSeob 2022. 3. 7. 01:05

문제

https://www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

문제풀이

STL stack을 이용해 풀었다.

- push는 s.push()

- pop은 스택이 비어있으면 -1을, 비어있지 않으면 s.top()을 출력한 후 s.pop()을 한다.

- size는 s.size()를 출력

- empty()는 s.empty()를 출력

- top은 스택이 비어있으면 -1을, 비어있지 않으면 s.top()을 출력한다.

 

코드

#include <iostream>
#include <stack>
using namespace std;

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

	int N(0), num(0);
	string cmd("");
	stack<int>s;
	cin >> N;
	while (N--) {
		cin >> cmd;
		if (cmd == "push") {
			cin >> num;
			s.push(num);
		}
		else if (cmd == "pop") {
			if (!s.empty()) {
				cout << s.top();
				s.pop();
			}
			else cout << -1;
		}
		else if (cmd == "size")
			cout << s.size();
		else if (cmd == "empty")
			cout << s.empty();
		else if (cmd == "top") {
			if (!s.empty())
				cout << s.top();							
			else cout << -1;
		}
		if (cmd != "push")
			cout << '\n';
	}
}