티스토리 뷰

알고리즘/Baekjoon

백준 10828: 스택 (C++)

개발하는 크롱 2020. 11. 21. 20:37
반응형

문제 링크: www.acmicpc.net/problem/10828

 

10828번: 스택

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

www.acmicpc.net

 

C++의 스택 STL을 사용해 문제를 해결했다.

아래 포스트 참고 :

crong-dev.tistory.com/13

 

[자료구조] 스택(stack) / 백준 10828 (C++)

지난 포스트에서 스택에 대해 알아보았다. 이전 포스트: https://crong-dev.tistory.com/10 [자료구조] 스택(stack) / 백준 10828 (C) 스택이란? 삽입과 제거가 한쪽 끝에서만 이루어지는 특수한 선형 리스트.

crong-dev.tistory.com

 

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

stack<int> st; //스택 생성. <>안에는 원소의 타입을 적어주면 된다

int main() {
	int N;
	scanf("%d", &N);

	for (int i = 0; i < N; i++) {
		string command;
		cin >> command;

		if (command == "push") {
			int x;
			cin >> x;
			st.push(x);
		}
		else if (command == "pop") {
			if (!st.empty()) {
				cout << st.top() << endl;
				st.pop();
			}
			else {
				cout << -1 << endl;
			}
		}
		else if (command == "size") {
			cout << st.size() << endl;
		}
		else if (command == "empty") {
			cout << st.empty() << endl;
		}
		else if (command == "top") {
			if (!st.empty()) {
				cout << st.top() << endl;
			}
			else {
				cout << -1 << endl;
			}
		}
	}

	return 0;
}

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함