class MyStack {
private Queue<Integer> a;// 输入队列
private Queue<Integer> b;// 输出队列
/** Initialize your data structure here. */
public MyStack() {
a=new LinkedList<>();
b=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
a.offer(x);//进队
while(!b.isEmpty()) {
a.offer(b.poll());//poll出队
}
Queue<Integer> temp=a;
a=b;
b=temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return b.poll();
}
/** Get the top element. */
public int top() {
return b.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return b.isEmpty();
}
}
用队列实现栈
最新推荐文章于 2020-05-25 10:05:39 发布