队列与栈
232. 用栈实现队列
题目链接 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
);
解法:栈1用来push,栈2用来pop,栈2是由栈1挨个pop过来的,这样相当于栈2反转了栈1的顺序,相当于把先进后出的顺序变成了先进先出;
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
handleStackOut();
return stackOut.pop();
}
public int peek() {
handleStackOut();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,则把stackIn全放入stackOut, 相当于把先进后出的顺序变成了先进先出
public void handleStackOut() {
if (!stackOut.isEmpty()) {
return;
}
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
225. 用队列实现栈
题目链接 请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
解法:用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1。
class MyStack {
Queue<Integer> queue1; // 和栈中保持一样元素的队列
Queue<Integer> queue2; // 辅助队列
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
// 先放在辅助队列中
queue2.offer(x);
while (!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
// 最后交换queue1和queue2,将元素都放到queue1中
Queue<Integer> queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll();
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}