[BOJ] 10828. 스택

동스토리 ㅣ 2020. 10. 17. 23:09

반응형

문제

www.acmicpc.net/problem/10828

 

10828번: 스택

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

www.acmicpc.net


해설

런타임에러: pop과 top을 하기 전에 배열에 인덱스를 벗어나는지 확인 후에 예외처리를 해줘야 한다.


코드

#include<iostream>
#include<algorithm>
#include<stack>
#include<string>

using namespace std;

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);

	int n;
	cin >> n;

	stack<int> q;
	string arr;

	while (n != 0) {

		cin >> arr;
		int s;
		if (arr == "push") {
			cin >> s;
			q.push(s);
		}
		else if (arr == "top") {
			if (!q.empty()) cout << q.top() << '\n';
			else cout << -1 << '\n';
		}
		else if (arr == "size") cout << q.size() << '\n';
		else if (arr == "pop") {
			if (!q.empty()) {
				cout << q.top() << '\n';
				q.pop();
			}
			else if (q.empty()) cout << -1 << '\n';
		}
		else if (arr == "empty") cout << q.empty() << '\n';

		n--;
	}

}

 

 

 

반응형

'Development > Algorithm' 카테고리의 다른 글

[BOJ] 10866. 덱  (0) 2020.10.17
[BOJ] 10845. 큐  (0) 2020.10.17
[BOJ] 10815. 숫자 카드  (0) 2020.10.17
[BOJ] 1920. 수 찾기  (0) 2020.10.17
[BOJ] 3085. 사탕 게임  (0) 2020.10.06