본문 바로가기

Study/BaekJoon

[백준 자바JAVA] 18258번 - 큐 2

728x90

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


● 문제

큐를 구현하면되는 아주 간단한 문제이다. 큐는 선입선출 자료구조로 말 그대로 먼저 들어간 요소가 먼저 나오는 방식이다. 자바에 있는 큐 라이브러리를 사용하면 맨 마지막에 있는 요소를 꺼내오는 함수가 없어 덱을 이용하여 구현하였다.

 


● 코드

import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        Deque<Integer> q = new LinkedList<>();
        int N = Integer.parseInt(br.readLine());

        for(int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine(), " ");

            String comment = st.nextToken();
            if(comment.equals("push")) {
                int num = Integer.parseInt(st.nextToken());
                q.offer(num);
            }

            else if(comment.equals("pop")) {
                Integer tmp = q.poll();
                if(tmp == null) {
                    sb.append(-1).append('\n');
                }
                else {
                    sb.append(tmp).append('\n');
                }
            }

            else if(comment.equals("size")) {
                sb.append(q.size()).append('\n');
            }

            else if(comment.equals("empty")) {
                if(q.isEmpty()) {
                    sb.append(1).append('\n');
                }
                else {
                    sb.append(0).append('\n');
                }
            }

            else if(comment.equals("front")) {
                Integer ite = q.peek();
                if(ite == null) {
                    sb.append(-1).append('\n');
                }
                else {
                    sb.append(ite).append('\n');
                }
            }

            else if(comment.equals("back")) {
                Integer it = q.peekLast();
                if(it == null) {
                    sb.append(-1).append('\n');
                }
                else {
                    sb.append(it).append('\n');
                }
            }

        }
        System.out.println(sb);
    }
}

for문이 아닌 while문과 switch문으로 구성하면 더욱 깔끔한 코드를 만들 수 있을 것 같다.

 

728x90