Updated:

1. 문제 링크

https://www.acmicpc.net/problem/10828

2. 사용 알고리즘

스택

3. 풀이

방법 1) 스택 직접 구현

방법 2) 라이브러리의 스택 이용

4. 소스 코드

4-1. C++

https://github.com/dev-aiden/problem-solving/blob/main/boj/10828.cpp

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
#include <iostream>
#include <stack>

using namespace std;

int main(void) {
    ios_base::sync_with_stdio(false);
    stack<int> s;
    int n; for (cin >> n; n--;) {
        string cmd; cin >> cmd;
        if (cmd == "push") {
            int num; cin >> num;
            s.push(num);
        }
        else if (cmd == "pop") {
            if (s.size() != 0) {
                cout << s.top() << "\n";
                s.pop();
            }
            else {
                cout << "-1" << "\n";
            }
        }
        else if (cmd == "size") {
            cout << s.size() << "\n";
        }
        else if (cmd == "empty") {
            cout << s.empty() << "\n";
        }
        else if (cmd == "top") {
            cout << (s.size() ? s.top() : -1) << "\n";
        }
    }
    return 0;
}

4-2. JAVA

https://github.com/dev-aiden/problem-solving/blob/main/boj/10828.java

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        Stack<Integer> s = new Stack<>();
        int n = Integer.parseInt(br.readLine());
        for(int i = 0; i < n; ++i) {
            String cmd = br.readLine();
            StringTokenizer st = new StringTokenizer(cmd);
            if(st.nextToken().equals("push")) {
                int num = Integer.parseInt(st.nextToken());
                s.push(num);
            } else if(cmd.equals("pop")) {
                if(s.size() != 0) {
                    sb.append(s.peek()).append("\n");
                    s.pop();
                } else {
                    sb.append("-1").append("\n");
                }
            } else if(cmd.equals("size")) {
                sb.append(s.size()).append("\n");
            } else if(cmd.equals("empty")) {
                sb.append(s.empty() ? 1 : 0).append("\n");
            } else if(cmd.equals("top")) {
                sb.append(s.size() != 0 ? s.peek() : -1).append("\n");
            }
        }
        System.out.println(sb);
    }
}

Updated:

Leave a comment