出自LeetCode225:只是用队列的offer、poll、isEmpty方法实现一个堆栈的存取。
其基本原理都是通过对出入队列的元素顺序进行逆向处理,由于java中可以用LinkedList来实现队列,因此在每次往队列中添加一个新元素时,都可以通过循环来将此元素移动到末尾,这样实现先进后出的特性。
1.使用一个队列实现
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
for(int i = 1; i < queue.size(); i++)
queue.offer(queue.poll());
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.size() == 0;
}
}
2.使用两个队列实现
此方法时刻保证a队列为空,在每次往a队列中添加元素时,新入的元素始终在队首,通过b队列将之前入队的元素逆序存入a队列中实现堆栈效果(即b队列中的元素顺序始终是和a队列offer的元素顺序相逆的)
class MyStack {
Queue<Integer> a;
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());
}
Queue tmp = a;
a = b;
b = tmp;
}
/** 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();
}
}

3358

被折叠的 条评论
为什么被折叠?



