题目地址(232. 用栈实现队列)

https://leetcode-cn.com/problems/implement-queue-using-stacks/

题目描述

  1. 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):
  2. 实现 MyQueue 类:
  3. void push(int x) 将元素 x 推到队列的末尾
  4. int pop() 从队列的开头移除并返回元素
  5. int peek() 返回队列开头的元素
  6. boolean empty() 如果队列为空,返回 true ;否则,返回 false
  7. 说明:
  8. 你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, is empty 操作是合法的。
  9. 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
  10. 进阶:
  11. 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
  12. 示例:
  13. 输入:
  14. ["MyQueue", "push", "push", "peek", "pop", "empty"]
  15. [[], [1], [2], [], [], []]
  16. 输出:
  17. [null, null, null, 1, 1, false]
  18. 解释:
  19. MyQueue myQueue = new MyQueue();
  20. myQueue.push(1); // queue is: [1]
  21. myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
  22. myQueue.peek(); // return 1
  23. myQueue.pop(); // return 1, queue is [2]
  24. myQueue.empty(); // return false
  25. 提示:
  26. 1 <= x <= 9
  27. 最多调用 100 pushpoppeek empty
  28. 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

前置知识


公司

  • 暂无

思路

232.用栈实现队列版本2.gif
使用两个栈来实现一个模拟队列

关键点


代码

  • 语言支持:Java

Java Code:

  1. class MyQueue {
  2. Stack<Integer> stackIn;
  3. Stack<Integer> stackOut;
  4. public MyQueue() {
  5. stackIn = new Stack<>();
  6. stackOut = new Stack<>();
  7. }
  8. public void push(int x) {
  9. stackIn.push(x);
  10. }
  11. public int pop() {
  12. dump();
  13. return stackOut.pop();
  14. }
  15. //查看栈顶元素 并不删除
  16. public int peek() {
  17. dump();
  18. return stackOut.peek();
  19. }
  20. public boolean empty() {
  21. return stackOut.isEmpty()&&stackIn.isEmpty();
  22. }
  23. //如果so为空的话讲si的数字放到so中 反之不交换
  24. public void dump() {
  25. if (stackOut.isEmpty()) {
  26. while (!stackIn.isEmpty()) {
  27. stackOut.push(stackIn.pop());
  28. }
  29. }
  30. }
  31. }

复杂度分析

令 n 为数组长度。

  • 时间复杂度:232. 用栈实现队列 - 图2#card=math&code=O%28n%29&id=B1CXR)
  • 空间复杂度:232. 用栈实现队列 - 图3#card=math&code=O%281%29&id=OQl9U)