본문 바로가기
알고리즘/스택,큐,덱

[java 백준] 실버 4/10845번 큐

by Meaning_ 2021. 8. 29.
728x90
반응형

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

 

10845번: 큐

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();
        LinkedList<Integer> queue = new LinkedList<>();
        int num = sc.nextInt();
        int n = 0;
        for (int i = 0; i < num; i++) {
            String order = sc.next();
            if (order.equals("push")) {
                n = sc.nextInt();
 
                queue.add(n);
            } else if (order.equals("front")) {
 
                if (queue.isEmpty()) {
                    sb.append(-1).append('\n');
                } else {
                    sb.append(queue.peek()).append('\n');
                }
 
            } else if (order.equals("back")) {
                if (queue.isEmpty()) {
                    sb.append(-1).append('\n');
                } else {
                    sb.append(queue.getLast()).append('\n');
                }
 
            } else if (order.equals("size")) {
                sb.append(queue.size()).append('\n');
            } else if (order.equals("pop")) {
 
                if (queue.isEmpty()) {
                    sb.append(-1).append('\n');
                } else {
                    sb.append(queue.remove()).append('\n');
                }
 
            } else if (order.equals("empty")) {
                if (queue.isEmpty()) {
                    sb.append(1).append('\n');
                } else {
                    sb.append(0).append('\n');
                }
            }
 
        }
        bw.write(sb.toString());
        bw.close();
 
    }
 
}
cs

 

 

LinkedList 라이브러리 


아래 링크에 LinkedList 라이브러리가 잘 정리되어있어서 참고해보면 좋을듯하다.

peekLast만 LinkedList 라이브러리에서 가져왔고, 나머지는 스택, 큐 라이브러리와 똑같다.

 

https://staticclass.tistory.com/99

 

04. [자바] LinkedList 생성자, 메서드

다른 컬렉션, 자료구조가 궁금하다면 아래의 링크를 클릭하시라💡 01. [자바] 컬렉션 프레임워크(Collections Framework) 컬렉션 프레임워크란? 다수의 데이터를 다루는 데 필요한 배열과 비슷하지만

staticclass.tistory.com

 

728x90
반응형

댓글