문제: https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
접근:
2년 전, 자료구조 수강 당시
c로 풀어본 이력이 있었다.
c++ stack 라이브러리를 활용하니까 확실히 간결하고 편했다.
별다른 코드 작성 없이
stack 메소드 활용해서 작성한게 전부이고
스택 비어있을 때 "-1" 출력 조건 정도만 덧붙여 작성하면 끝
소스코드:
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
void push();
void pop();
void size();
void empty();
void top();
int main() {
// ios:: sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string str = "";
cin >> str;
if (str == "push") {
push();
}
if (str == "pop") {
pop();
}
if (str == "size") {
cout << s.size() << "\n";
}
if (str == "empty") {
empty();
}
if (str == "top") {
top();
}
}
return 0;
}
void push() {
int num;
cin >> num;
s.push(num);
}
void pop() {
if (s.empty()) {
cout << "-1\n";
return;
}
cout << s.top() << "\n";
s.pop();
}
void empty() {
if (s.empty())
cout << "1\n";
else
cout << "0\n";
}
void top(){
if (s.empty()){
cout << "-1\n";
return;
}
cout << s.top() << "\n";
}

'코딩테스트 > 백준' 카테고리의 다른 글
[백준2178][c++] 미로 찾기 (0) | 2023.04.17 |
---|---|
[백준17298][c++] 오큰수 (0) | 2023.04.16 |
[백준1159][c++] 농구 경기 (0) | 2023.04.14 |
[백준10988][c++] 팰린드롬인지 확인하기 (0) | 2023.04.14 |
백준 4949번] 균형잡힌 세상 코드 리뷰 (1) | 2022.10.04 |