본문 바로가기
코딩/백준-자바

백준 10845번: 큐

by 철없는민물장어 2023. 1. 24.
728x90

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

 

10845번: 큐

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

www.acmicpc.net

 

큐를 만들어서 입력에 맞게 명령어를 처리해 주면 된다.

 

간단하게 자바 라이브러리를 사용했다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class P10845 {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());

		Queue<Integer> q = new LinkedList<>();

		int last = -1;
		for (int i = 0; i < n; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());

			String instruction = st.nextToken();

			if (instruction.equals("push")) {
				last = Integer.parseInt(st.nextToken());
				q.add(last);

			} else if (instruction.equals("pop")) {
				if (q.isEmpty())
					System.out.println(-1);
				else
					System.out.println(q.poll());
			} else if (instruction.equals("size")) {
				System.out.println(q.size());
			} else if (instruction.equals("empty")) {
				if (q.isEmpty())
					System.out.println(1);
				else
					System.out.println(0);
			} else if (instruction.equals("front")) {
				if (q.isEmpty())
					System.out.println(-1);
				else {
					System.out.println(q.peek());
				}
			} else if (instruction.equals("back")) {
				if (q.isEmpty())
					System.out.println(-1);
				else {
					System.out.println(last);
				}
			}
		}
	}

}

그런데 Queue 라이브러리로는 최근에 넣은 수를 볼 수 있는 기능이 없어서

따로 int last라는 변수를 만들어서

수를 push할 때마다 last의 값을 갱신시켜주고,

back이라는 명령어가 들어왔을 때 가장 최근에 넣은 값인 last를 출력하도록 했다.

 

728x90

댓글