백준 10845번 (큐)

김경욱·2025년 9월 12일

백준

목록 보기
78/121

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.*;

import static java.util.Collections.*;

public class Main {
public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

   int N = Integer.parseInt(br.readLine());



   Deque<Integer> Q = new ArrayDeque<>();

   for (int i = 0 ; i < N; i++)
   {

       String line = br.readLine();

       String[] parts = line.split(" ");





       if (parts[0].equals("push"))
       {
           Q.add(Integer.parseInt(parts[1]));
       }

       if (parts[0].equals("front"))
       {
           if (Q.isEmpty())
           {
               System.out.println(-1);
               continue;
           }
           System.out.println(Q.peek());
       }

       if (parts[0].equals("back"))
       {
           if (Q.isEmpty())
           {
               System.out.println(-1);
               continue;
           }

           System.out.println(Q.peekLast());
       }

       if (parts[0].equals("size"))
       {
           System.out.println(Q.size());
       }

       if(parts[0].equals("empty"))
       {
           if (Q.isEmpty())
           {
               System.out.println(1);
           }
           else{
               System.out.println(0);
           }
       }

       if (parts[0].equals("pop"))
       {

           if (Q.isEmpty())
           {
               System.out.println(-1);
               continue;
           }



           System.out.println(Q.peek());
           Q.pop();


       }


    }









}
}

처음 배우는 큐이다. 스택은 가장 늦게 들어온게 가장 먼저 나가는 구조이고 큐는 가장 먼저 들어온게 가장 먼저 나가는 구조이다. 마지막 값을 구하기 위해서 큐를 Deque로 설정하였다.

0개의 댓글