-
10845번 - 큐알고리즘/백준 2023. 6. 6. 13:10
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); LinkedList<Integer> queue = new LinkedList<>(); StringTokenizer st; StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(br.readLine()); String command; for(int i=0;i<N;i++) { st = new StringTokenizer(br.readLine()); command = st.nextToken(); if(command.equals("push")) { queue.offer(Integer.parseInt(st.nextToken())); } else if(command.equals("front")) { sb.append(queue.isEmpty() ? -1+"\n" : queue.peek()+"\n"); } else if(command.equals("back")) { sb.append(queue.isEmpty() ? -1+"\n" : queue.peekLast()+"\n"); } else if (command.equals("size")) { sb.append(queue.size()+"\n"); } else if (command.equals("empty")) { sb.append(queue.isEmpty() ? 1+"\n" : 0+"\n"); } else { sb.append(queue.isEmpty() ? -1+"\n" : queue.pop()+"\n"); } } System.out.println(sb); br.close(); } }
역시 문제의 의도와 다르지만 자바의 LinkedList를 이용해 간단하게 해결할 수 있습니다.
먼저 command를 받고 각 커맨드에 따라 명령을 수행하면 끝입니다.
switch문보다 if else문이 조금 더 빠르기 때문에 if else문으로 구현하고 StringBuilder를 사용했습니다.
'알고리즘 > 백준' 카테고리의 다른 글
1676번 - 팩토리얼 0의 개수 (2) 2023.06.06 10866번 - 덱 (0) 2023.06.06 10828번 - 스택 (2) 2023.06.06 10816번 - 숫자 카드 2 (1) 2023.06.06 10814번 - 나이순 정렬 (1) 2023.06.06