AcWing打卡活动
《剑指Offer》打卡活动
周一第八题 用两个栈实现队列
/**
* 用两个栈实现队列
* 该题无需考虑时间复杂度,只需要实现操作即可
* create by yifeng
*/
public class Question09 {
public static void main(String[] args) {
}
class MyQueue {
Stack<Integer> stack;
Stack<Integer> cache;
/** Initialize your data structure here. */
public MyQueue() {
stack = new Stack();
cache = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
// pop操作,将stack所有元素压入cache中,cache的弹出的第一个元素为stack中的最后一个元素
public int pop() {
int k;
while (!empty()) {
cache.push(stack.pop());
}
k = cache.pop(); // 将第一个元素弹出,即stack的最后一个元素
while (!cache.empty()) {
stack.push(cache.pop());
}
return k;
}
// 与pop操作类似,只是不需要将元素弹出
public int peek() {
int k;
while (!empty()) {
cache.push(stack.pop());
}
k = cache.peek(); // 直接获取第一个即可,不需要弹出
// 将元素压入stack中
while (!cache.empty()) {
stack.push(cache.pop());
}
return k;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.empty();
}
}
}