class MyStack {
/** Initialize your data structure here. */
private ArrayDeque<Integer> q1=new ArrayDeque<>();
private ArrayDeque<Integer> q2=new ArrayDeque<>();
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q2.offer(x);
while(q2.size()>1)
{
q1.offer(q2.peek());
q2.poll();
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int top= top();
q2.poll();
return top;
}
/** Get the top element. */
public int top() {
if(q2.isEmpty())
{
for(int i=0;i<q1.size()-1;i++)
{
q1.offer(q1.peek()); q1.poll();
}
q2.offer(q1.peek());
q1.poll();
}
return q2.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty()&&q2.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
方法2:
class MyStack {
/** Initialize your data structure here. */
private ArrayDeque<Integer> q=new ArrayDeque<>();
public MyStack()
{
}
/** Push element x onto stack. */
public void push(int x) {
q.offer(x);
for(int i=0;i<q.size()-1;i++)
{
q.offer(q.peek());q.poll();
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int x=q.peek();
q.poll();
return x;
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/