AcWing 20. 用两个栈实现队列 - Java
原题链接
简单
作者:
KYCygni
,
2021-04-04 04:44:00
,
所有人可见
,
阅读 286
Java 代码
class MyQueue {
Stack s1;
Stack s2;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack();
s2 = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while (!s1.empty())
s2.push(s1.pop());
int b = (int)s2.pop();
while (!s2.empty())
s1.push(s2.pop());
return b;
}
/** Get the front element. */
public int peek() {
while (!s1.empty())
s2.push(s1.pop());
int b = (int)s2.peek();
while (!s2.empty())
s1.push(s2.pop());
return b;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty();
}
}