🔑알고리즘/baekjoon

백준 10845 : 큐 - 자바(java) 문제 풀이

pkyung 2022. 5. 10. 12:40
반응형

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

 

 

10845번: 큐

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

www.acmicpc.net

 

 

문제 이름을 보면 알 수 있듯이 큐를 사용하고 조건에 맞게 문제를 풀면 된다. 

 

 

BufferedReader와 BufferedWriter를 사용하였고, contains()를 활용해 문자열을 조건에 넣었다. 

 

 

front는 element를 활용하면 되는데 back을 어떻게 해결할까 고민을 했다.

 

iterator를 활용해야하나? 생각도 했지만 hasNext() 를 활용하면 마지막 next()의 값을 빼낼 수 없을 것 같아서 push 입력을 받을 때마다 변수 rear에 값을 저장하는 방법을 사용했다.

 

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));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		Queue<Integer> queue = new LinkedList<>();
		
		int n = Integer.parseInt(br.readLine());
		int rear = 0;
		for(int i = 0; i < n; i++) {
			String input = br.readLine();
			
			if(input.contains("push")) {
				String[] pushInput = input.split(" ");
				queue.add(Integer.parseInt(pushInput[1]));
				rear = Integer.parseInt(pushInput[1]);
			}
			else if(input.contains("pop")) {
				if(queue.isEmpty()) {
					bw.write("-1\n");
				}
				else {
					bw.write(queue.poll() + "\n");
				}
			}
			else if(input.contains("size")){
				bw.write(queue.size()+"\n");
			}
			else if(input.contains("empty")) {
				if(queue.isEmpty()) {
					bw.write("1\n");
				}
				else {
					bw.write("0\n");
				}
			}
			else if(input.contains("front")) {
				if(queue.isEmpty()) {
					bw.write("-1\n");
				}
				else {
					bw.write(queue.element()+"\n");
				}
			}
			else if(input.contains("back")) {
				if(queue.isEmpty()) {
					bw.write("-1\n");
				}
				else {
					bw.write(rear+"\n");
				}
			}
			
			
		}
		bw.flush();

	}

}

 

 

해결되었다.

반응형