공부/백준

[백준-10845] 큐 - Java

빈v 2022. 6. 9. 20:36
728x90

 

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

 

10845번: 큐

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

www.acmicpc.net

 

백준 10845번 큐 자바 풀이

난이도: 실버4

 

 

큐를 구현하는 문제이다.

push일 경우 queue.add()를 사용하여 구현하고,

pop일 경우 queue.poll()을 이용하여 구현하고,

size일 경우 queue.size()를 이용하여 구현하고,

empty일 경우 queue.isEmpty()를 이용하여 true/false 여부로 구현하고,

front일 경우 queue.peek()으로 구현하고,

back일 경우 마지막으로 queue.add()일 때 저장해놓은 변수로 확인 가능하도록 구현한다.

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class back10845 {
    public static void main(String args[]) throws NumberFormatException, IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int n=Integer.parseInt(br.readLine());
        Queue<Integer> queue=new LinkedList<>();
        int back=0;
        for(int i=0;i<n;i++){
            String str=br.readLine();
            if(str.contains("push")){
                String a[]=str.split(" ");
                queue.add(Integer.parseInt(a[1]));
                back=Integer.parseInt(a[1]);
            }else if(str.contains("pop")){
                if(queue.isEmpty())
                    sb.append(-1).append('\n');
                else
                    sb.append(queue.poll()).append('\n');
            }else if(str.contains("size")){
                sb.append(queue.size()).append('\n');
               
            }else if(str.contains("empty")){
                if(queue.isEmpty())
                    sb.append(1).append('\n');
                else
                    sb.append(0).append('\n');
            }else if(str.contains("front")){
                if(queue.isEmpty())
                    sb.append(-1).append('\n');
                else
                    sb.append(queue.peek()).append('\n');
            }else{
                if(queue.isEmpty())
                    sb.append(-1).append('\n');
                else
                    sb.append(back).append('\n');
            }
        }
        System.out.println(sb);
    }
}
728x90
반응형