알고리즘/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을 사용해 문제를 해결했다.
아래 포스트 참고 :
[자료구조] 스택(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;
}
반응형