Updated:

1. 문제 링크

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

2. 사용 알고리즘

3. 풀이

방법 1) 큐 직접 구현

방법 2) 라이브러리의 큐 이용

4. 소스 코드

4-1. C++

https://github.com/dev-aiden/problem-solving/blob/main/boj/10845.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 <queue>

using namespace std;

queue<int> q;

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

4-2. JAVA

https://github.com/dev-aiden/problem-solving/blob/main/boj/10845.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
38
39
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
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();
        Queue<Integer> q = new LinkedList<>();
        int n = Integer.parseInt(br.readLine());
        int num = 0;
        for(int i = 0; i < n; ++i) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            String cmd = st.nextToken();
            if(cmd.equals("push")) {
                num = Integer.parseInt(st.nextToken());
                q.offer(num);
            } else if(cmd.equals("pop")) {
                if(q.isEmpty()) sb.append("-1\n");
                else sb.append(q.poll()).append("\n");
            } else if(cmd.equals("size")) {
                sb.append(q.size()).append("\n");
            } else if(cmd.equals("empty")) {
                sb.append(q.isEmpty() ? 1 : 0).append("\n");
            } else if(cmd.equals("front")) {
                if(q.isEmpty()) sb.append("-1\n");
                else sb.append(q.peek()).append("\n");
            } else if(cmd.equals("back")) {
                if(q.isEmpty()) sb.append("-1\n");
                else sb.append(num).append("\n");
            }
        }
        System.out.println(sb);
    }
}

Updated:

Leave a comment