用栈来模拟一个队列,要求实现队列的两个基本操作:入队、出队。

    image.png

    既然我们拥有两个栈,那么可以让其中一个栈作为队列的入口,负责插入新元素;另一个栈作为队列的出口,负责移除老元素。

    image.png

    image.png

    image.png

    队列的主要操作无非有两个:入队和出队。
    在模拟入队操作时,每一个新元素都被压入到栈 A 当中。

    让元素 1 入队。
    image.png
    image.png
    让元素 2 入队。
    image.png
    image.png
    让元素 3 入队。
    image.png
    image.png

    这时,我们希望最先入队的元素1出队,需要怎么做呢?

    让栈 A 中的所有元素按顺序出栈,再按照出栈顺序压入栈 B。这样一来,元素从栈 A 弹出并压入栈 B 的顺序是 3、2、1,和当初进入栈 A 的顺序 1、2、3 是相反的。

    image.png
    此时让元素 1 出队,也就是让元素 1 从栈 B 中弹出。
    image.png
    让元素 2 出队。
    image.png
    image.png
    让元素 4 入队。
    image.png
    image.png
    此时出队操作仍然从栈 B 中弹出元素。
    让元素 3 出队。
    image.png
    image.png
    image.png
    让元素 4 出队。
    image.png

    1. /**
    2. * Initialize your data structure here.
    3. */
    4. var MyQueue = function() {
    5. this.input = []
    6. this.output = []
    7. };
    8. /**
    9. * Push element x to the back of queue.
    10. * @param {number} x
    11. * @return {void}
    12. */
    13. MyQueue.prototype.push = function(x) {
    14. this.input.push(x)
    15. };
    16. /**
    17. * Removes the element from in front of queue and returns that element.
    18. * @return {number}
    19. */
    20. MyQueue.prototype.pop = function() {
    21. if(!this.output.length) {
    22. while(this.input.length) {
    23. this.output.push(this.input.pop())
    24. }
    25. }
    26. return this.output.pop()
    27. };
    28. /**
    29. * Get the front element.
    30. * @return {number}
    31. */
    32. MyQueue.prototype.peek = function() {
    33. if(!this.output.length) {
    34. while(this.input.length) {
    35. this.output.push(this.input.pop())
    36. }
    37. }
    38. return this.output[this.output.length - 1]
    39. };
    40. /**
    41. * Returns whether the queue is empty.
    42. * @return {boolean}
    43. */
    44. MyQueue.prototype.empty = function() {
    45. if(this.input.length || this.output.length){
    46. return false
    47. } else{
    48. return true
    49. }
    50. };
    51. /**
    52. * Your MyQueue object will be instantiated and called as such:
    53. * var obj = new MyQueue()
    54. * obj.push(x)
    55. * var param_2 = obj.pop()
    56. * var param_3 = obj.peek()
    57. * var param_4 = obj.empty()
    58. */