반응형
import java.util.Stack;
public class QueueByStack {
public static void main(String[] args) {
MyQueue queue = new MyQueue();
}
static class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void offer(int x) {
s1.push(x);
}
public int poll() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.pop();
}
public int peek() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.peek();
}
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
}
}
반응형
'Algorithm' 카테고리의 다른 글
Reverse Queue with Java (0) | 2024.04.06 |
---|---|
Reverse Queue with Stack in Java (0) | 2024.04.06 |
BFS and DFS with Java (1) | 2024.04.06 |
BFS and DFS with Java (0) | 2024.03.24 |
DFS and BFS (0) | 2024.03.24 |