
난이도: ★☆☆☆☆ • solved on: 2025-11-21

자료구조
알고리즘/기법
핵심 키워드
- 문제 분해
- 원래 문제 의도는 스택 2개로 큐를 직접 구현하는 것이다.
- 하지만 자바의
ArrayDeque를 큐처럼 사용하는 방식이다.
핵심 로직 흐름
push(x): inStack에 push pop(): outStack이 비어 있으면 inStack 모두 outStack으로 이동, 그 후 pop peek(): outStack이 비어 있으면 이동, 그 후 peek
- 이렇게 하면 각 원소는 이동을 딱 한 번만 하므로 평균 O(1) 로 동작한다.
예외 처리
- 비어 있는 큐에서 pop 혹은 peek이 호출되지 않도록 주의한다.
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Queue<String> queue = new ArrayDeque<>();
int n = Integer.parseInt(br.readLine());
String line;
for (int i = 0; i < n; i++) {
line = br.readLine();
String[] arr = line.split(" ");
if (arr[0].equals("1")) {
queue.add(arr[1]);
} else if (arr[0].equals("2")) {
queue.poll();
} else if (arr[0].equals("3")) {
System.out.println(queue.peek());
} else {
System.err.println("undefined command " + arr[0]);
}
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Deque<Integer> inStack = new ArrayDeque<>();
Deque<Integer> outStack = new ArrayDeque<>();
int q = Integer.parseInt(br.readLine());
while (q-- > 0) {
String[] cmd = br.readLine().split(" ");
if (cmd[0].equals("1")) { // enqueue
inStack.push(Integer.parseInt(cmd[1]));
}
else if (cmd[0].equals("2")) { // dequeue
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
outStack.pop();
}
else if (cmd[0].equals("3")) { // peek
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
System.out.println(outStack.peek());
}
}
}
}
비슷한 유형:
확장 문제: