• 문제 링크
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
• 풀이 과정
Queue(FIFO) 자료구조에 관련된 기본적인 동작들을 구현하는 문제.
이전에 풀이한 10828 문제와 전체적인 구현 방식은 동일하다.
추가로 큐의 가장 뒤에 있는 정수를 출력하는 back 명령어를 구현 시
큐의 가장 뒤에 있는 정수는 가장 마지막에 offer, 또는 add 한 값으로, 이를 back 변수에 갱신해주고
back 명령이 주어질 때 그대로 back 변수에 저장된 값을 출력한다.
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
Queue<Integer> q = new LinkedList<>();
int back = 0;
for (int i = 0; i < n; i++) {
String[] comm = br.readLine().split(" ");
if (comm[0].equals("push")) {
q.offer(Integer.parseInt(comm[1]));
back = Integer.parseInt(comm[1]);
}
if (comm[0].equals("pop"))
if (q.isEmpty())
bw.write(-1 + "\n");
else
bw.write(q.poll() + "\n");
if (comm[0].equals("size"))
bw.write(q.size() + "\n");
if (comm[0].equals("empty"))
if (q.isEmpty())
bw.write(1 + "\n");
else
bw.write(0 + "\n");
if (comm[0].equals("front"))
if (q.isEmpty())
bw.write(-1 + "\n");
else
bw.write(q.peek() + "\n");
if (comm[0].equals("back"))
if (q.isEmpty())
bw.write(-1 + "\n");
else
bw.write(back + "\n");
}
bw.flush();
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 9012 괄호 - Data Structure / Java (0) | 2022.06.13 |
---|---|
[백준] 10866 덱 - Data Structure / Java (0) | 2022.06.12 |
[백준] 10828 스택 - Data Structure / Java (0) | 2022.06.12 |
[백준] 1697 숨바꼭질 - Graph Theory / Java (0) | 2022.06.11 |
[백준] 16953 A → B - Graph Theory / Java (0) | 2022.06.10 |
댓글