728x90
https://www.acmicpc.net/problem/10845
큐를 만들어서 입력에 맞게 명령어를 처리해 주면 된다.
간단하게 자바 라이브러리를 사용했다.
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
'코딩 > 백준-자바' 카테고리의 다른 글
[자바] 백준 2748번: 피보나치 수2 (0) | 2023.01.26 |
---|---|
[자바] 백준 2805번: 나무 자르기 (0) | 2023.01.25 |
[자바] 백준 2003번: 수들의 합2 (0) | 2023.01.24 |
[자바] 백준 2960번: 에라토스테네스의 체 (0) | 2023.01.21 |
[자바] 백준 1700번: 멀티탭 스케줄링 (0) | 2023.01.20 |
댓글