AcWing 20. 用两个栈实现队列_Java
原题链接
简单
作者:
0918k
,
2020-05-19 09:00:34
,
所有人可见
,
阅读 586
class MyQueue {
// 从队尾入 从队头出
/** Initialize your data structure here. */
// 一个主栈 一个缓存
Stack<Integer> stk = new Stack<>();
Stack<Integer> cache = new Stack<>();
public MyQueue() {
}
// 两个栈实现队列 push 插入队尾 pop 队首元素弹出返回改元素 peek 返回对手 empty 是否为空
/** Push element x to the back of queue. */
public void push(int x) {
stk.push(x);
}
public void copy(Stack<Integer> a, Stack<Integer> b){
while(a.size()!=0){
b.push(a.peek());
a.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
copy(stk,cache); //反转一次
int res = cache.peek(); //此时栈顶就是队头就是栈底
cache.pop(); //弹出
copy(cache, stk); //反转回来
return res;
}
/** Get the front element. */
public int peek() {
copy(stk, cache);
int res = cache.peek(); //得到队头
copy(cache, stk);
return res;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stk.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/