class MyQueue {
private Stack<Integer> a;// 输入栈
private Stack<Integer> b;// 输出栈
public MyQueue() {
a=new Stack<>();
b=new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(b.isEmpty()) {
while(!a.isEmpty()) {
b.push(a.pop());
}
}
return b.pop();
}
/** Get the front element. */
public int peek() {
if(b.isEmpty()) {
while(!a.isEmpty()) {
b.push(a.pop());
}
}
return b.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return a.isEmpty()&&b.isEmpty();
}
}
用栈实现队列
最新推荐文章于 2023-08-26 20:04:46 发布