본문 바로가기
CS/Algorithm

[알고리즘] 10866 덱

by 별토끼. 2018. 3. 13.
반응형

[알고리즘] 10866 덱


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



[풀이]

  • 덱의 기본 개념을 알기 위한 문제
  • 덱은 양 끝에서만 자료를 넣고 양 끝에서 뺄 수 있는 자료구조이다.
  • 덱을 구현하는 문제.
  • System.out.println(deque.pollLast());을 하면 poll과 동시에 출력한다.

[코드]

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
package algorithm_basic;
 
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
 
public class p_10866 {
 
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int line_num=scan.nextInt();
        scan.nextLine();
        Deque<Integer> deque = new LinkedList<>();
 
        for(int i=0;i<line_num;i++) {
            String[] line = scan.nextLine().split(" ");
            String cmd = line[0];
            
            
            if(cmd.equals("push_front")) {
                int cmd_num = Integer.parseInt(line[1]);
                deque.offerFirst(cmd_num);
            }else if(cmd.equals("push_back")) {
                int cmd_num = Integer.parseInt(line[1]);
                deque.offerLast(cmd_num);
            }else if(cmd.equals("pop_front")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.pollFirst());
                }else
                    System.out.println("-1");
            }else if(cmd.equals("pop_back")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.pollLast());
                }else
                    System.out.println("-1");
            }else if(cmd.equals("size")) {
                System.out.println(deque.size());
            }else if(cmd.equals("empty")) {
                if(deque.isEmpty()) {
                    System.out.println("1");
                }else 
                    System.out.println("0");
            }else if(cmd.equals("front")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.peekFirst());
                }else
                    System.out.println("-1");
            }else if(cmd.equals("back")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.peekLast());
                }else
                    System.out.println("-1");
            }
            
        }
    }
 
}
 
cs


반응형

'CS > Algorithm' 카테고리의 다른 글

[알고리즘] 10820 문자열 분석  (0) 2018.03.17
[알고리즘] 10808 알파벳  (0) 2018.03.17
[알고리즘] 1158 조세퍼스 문제  (0) 2018.03.13
[알고리즘] 10845 큐  (0) 2018.03.12
[알고리즘] 1406 에디터  (0) 2018.03.10

댓글