Algorithm/BOJ

[백준 알고리즘/C++/스택] 10828 스택

pinevienna 2021. 4. 24. 18: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
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    int n, val;
    stack<int> s;
    string func;
 
    cin >> n;
    while (n--) {
        cin >> func;
        if (func == "push") {
            cin >> val;
            s.push(val);
        }
        else if (func == "pop") {
            if (s.empty()) {
                cout << -1 << "\n";
                continue;
            }
 
            cout << s.top() << "\n";
            s.pop();
        }
        else if (func == "size"
            cout << s.size() << "\n";
        else if (func == "empty"
            cout << s.empty() << "\n";
        else if (func == "top") {
            if (s.empty())
                cout << -1 << "\n"
            else
                cout << s.top() << "\n";
        }
    }
}
cs