232.用栈实现队列
解题思路:双栈
package leadcode;
import java.util.Deque;
import java.util.LinkedList;
/**
* @author : icehill
* @description : 用栈实现队列
* 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
* 实现 MyQueue 类:
* void push(int x) 将元素 x 推到队列的末尾
* int pop() 从队列的开头移除并返回元素
* int peek() 返回队列开头的元素
* boolean empty() 如果队列为空,返回 true ;否则,返回 false
* 说明:
* 你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
* 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* 解题思路:
* 题目描述了一大堆,其实就是让你用栈来实现队列(用先进后出,实现先进先出的数据结构)
* 我们使用双栈即可解决
* 1.定义一个in栈,一个out栈(java用LinkedList队列模拟,只使用push,peek,pop,isEmpty)
* 2.对于所有push,都用in.push处理
* 3.对于所有获取栈顶操作,pop或者peek,首先判断out栈是否为空,不为空的话把in全部pop转移到out中
* 保证out的栈顶一定是最先in入栈的元素(对于每个元素,至多入栈和出栈各两次,故均摊复杂度为 O(1))
* 时间复杂度:O(1) 空间复杂度:O(n)
* @date : 2021-05-23
*/
public class Solution232 {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(1);
myQueue.push(2);
System.out.println(myQueue.peek());
System.out.println(myQueue.pop());
System.out.println(myQueue.peek());
System.out.println(myQueue.empty());
}
public static class MyQueue {
//栈操作
Deque<Integer> in;
Deque<Integer> out;
public MyQueue() {
in = new LinkedList<>();
out = new LinkedList<>();
}
public void push(int x) {
in.push(x);
}
public int pop() {
in2Out();
return out.pop();
}
/**
* Get the front element.
*/
public int peek() {
in2Out();
return out.peek();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
/**
* 关键代码
* 如果out栈是空,才把in栈转移到out里面,这样保证out的栈顶,肯定是in的第一个
* 也就是模拟了队列的先进先出
*/
private void in2Out() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
}
}