所用示例均出自力扣https://leetcode-cn.com/
题解参考力扣和https://cyc2018.github.io/CS-Notes/#/notes/Leetcode 题解 - 目录1
用队列实现栈
思路:
- 创建两个队列,一个用于输入in,一个用于输出out。
- 添加的时候将数据加到in中,然后将out中的数据都加到in中,此时in队列的头就是刚压入的数。再将in, out互换,保证压入队列为空。
- 对输出队列进行poll(),peek()等操作。
补:队列的相关操作
add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素
class MyStack {
private Queue<Integer> in;
private Queue<Integer> out;
/** Initialize your data structure here. */
public MyStack() {
in = new LinkedList<>();
out = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
in.add(x);
while(!out.isEmpty()){
in.add(out.poll());
}
Queue temp = in;
in = out;
out = temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return out.poll();
}
/** Get the top element. */
public int top() {
return out.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return out.isEmpty();
}
}
- 用一个队列实现,队列的压入是添加到队列尾部;
- 每添加一个数字,就将该数的前size-1个数都取出,重新压入,这样就保证添加的数据在队列的头部;
- 对给队列进行poll(),peek()操作。
class MyStack {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}