请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。

    1. 输入:
    2. ["MyQueue", "push", "push", "peek", "pop", "empty"]
    3. [[], [1], [2], [], [], []]
    4. 输出:
    5. [null, null, null, 1, 1, false]
    6. 解释:
    7. MyQueue myQueue = new MyQueue();
    8. myQueue.push(1); // queue is: [1]
    9. myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
    10. myQueue.peek(); // return 1
    11. myQueue.pop(); // return 1, queue is [2]
    12. myQueue.empty(); // return false
    1. var MyQueue = function () {
    2. this.stack = []
    3. this._stack = []
    4. };
    5. MyQueue.prototype.move = function (x) {
    6. if (this._stack.length) {
    7. return true;
    8. }
    9. this._stack = this.stack.reverse().concat(this._stack)
    10. this.stack = []
    11. }
    12. /**
    13. * @param {number} x
    14. * @return {void}
    15. */
    16. MyQueue.prototype.push = function (x) {
    17. this.stack.push(x)
    18. };
    19. /**
    20. * @return {number}
    21. */
    22. MyQueue.prototype.pop = function () {
    23. this.move()
    24. return this._stack.pop()
    25. };
    26. /**
    27. * @return {number}
    28. */
    29. MyQueue.prototype.peek = function () {
    30. this.move()
    31. return this._stack[this._stack.length - 1]
    32. };
    33. /**
    34. * @return {boolean}
    35. */
    36. MyQueue.prototype.empty = function () {
    37. return !this._stack.length && !this.stack.length
    38. };
    39. /**
    40. * Your MyQueue object will be instantiated and called as such:
    41. * var obj = new MyQueue()
    42. * obj.push(x)
    43. * var param_2 = obj.pop()
    44. * var param_3 = obj.peek()
    45. * var param_4 = obj.empty()
    46. */

    image.png