用栈实现队列

题目描述:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:双栈实现队列

MyQueue的2个栈分别为inStack和outStack,inStack用来入队列,outStack用来出队列,几个方法的主要实现逻辑如下:

  • push(int x):将x入栈inStack。
  • pop():如果栈outStack不为空,直接从outStack中出栈一个;如果outStack为空,则如果inStack不为空,将inStack的全部元素出栈并且入栈outStack,然后从栈outStack中出栈一个,如果inStack也为空,则抛出异常该队列为空。
  • peek():如果栈outStack不为空,返回outStack的栈顶元素;如果outStack为空,则如果inStack不为空,将inStack的全部元素出栈并且入栈outStack,然后返回outStack的栈顶元素,如果inStack也为空,则抛出异常该队列为空。
  • empty():如果inStack和outStack都为空,返回true;否则返回true。
  1. import java.util.Stack;
  2. public class LeetCode_232 {
  3. public static void main(String[] args) {
  4. MyQueue myQueue = new MyQueue();
  5. myQueue.push(1); // queue is: [1]
  6. myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
  7. System.out.println(myQueue.peek() == 1); // return 1
  8. System.out.println(myQueue.pop() == 1); // return 1, queue is [2]
  9. System.out.println(myQueue.empty()); // return false
  10. }
  11. }
  12. class MyQueue {
  13. private Stack<Integer> inStack;
  14. private Stack<Integer> outStack;
  15. /**
  16. * Initialize your data structure here.
  17. */
  18. public MyQueue() {
  19. inStack = new Stack<>();
  20. outStack = new Stack<>();
  21. }
  22. /**
  23. * Push element x to the back of queue.
  24. */
  25. public void push(int x) {
  26. inStack.push(x);
  27. }
  28. /**
  29. * Removes the element from in front of queue and returns that element.
  30. */
  31. public int pop() {
  32. if (outStack.isEmpty()) {
  33. if (inStack.isEmpty()) {
  34. throw new RuntimeException("stack is empty.");
  35. } else {
  36. while (!inStack.isEmpty()) {
  37. outStack.push(inStack.pop());
  38. }
  39. return outStack.pop();
  40. }
  41. } else {
  42. return outStack.pop();
  43. }
  44. }
  45. /**
  46. * Get the front element.
  47. */
  48. public int peek() {
  49. if (outStack.isEmpty()) {
  50. if (inStack.isEmpty()) {
  51. throw new RuntimeException("stack is empty.");
  52. } else {
  53. while (!inStack.isEmpty()) {
  54. outStack.push(inStack.pop());
  55. }
  56. return outStack.peek();
  57. }
  58. } else {
  59. return outStack.peek();
  60. }
  61. }
  62. /**
  63. * Returns whether the queue is empty.
  64. */
  65. public boolean empty() {
  66. return inStack.isEmpty() && outStack.isEmpty();
  67. }

【每日寄语】 每天吃一颗糖,然后告诉自己:今天的日子,果然又是甜的。