Skip to content

Latest commit

 

History

History
94 lines (66 loc) · 2.67 KB

232.用栈实现队列.md

File metadata and controls

94 lines (66 loc) · 2.67 KB

难度:简单

类型: 栈

题目:

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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: 输入: ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false]

解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false

思路:

队列的特点是先进先出,而栈的特点是后进先出,想要用栈的特点实现队列的效果,那么就需要两个栈来配合实现。

比如现在有一个队列: const queue = [1, 2, 3, 4, 5], pop 取出来的结果应该是 1, 2, 3, 4, 5

现在用栈去实现的话,const stack = [1, 2, 3, 4, 5], 通过 pop 取值的时候,取出来的值是 5,4, 3,2, 1 那么就需要需要将这些元素 push 到另外一个栈中:const stack2 = [5, 4, 3, 2, 1], 此时再执行 pop 操作的时候 就是 1, 2, 3, 4, 5 了。

实现:

JavaScript:

const MyQueue = function () {
    this.stack1 = []
    this.stack2 = []
}

MyQueue.prototype.push = function (val) {
    this.stack1.push(val)
}

MyQueue.prototype.pop = function () {
    // 当 stack2 为空时
    if (!this.stack2.length) {
        // 当 stack1 不为空时
        while (this.stack1.length) {
            this.stack2.push(this.stack1.pop())
        }
    }
    // 只操作 stack2 出栈
    return this.stack2.pop()
}

// 返回第一个元素,与 pop 的区别:不会将元素移出栈
MyQueue.prototype.peek = function () {
    if (!this.stack2.length) {
        while (this.stack1.length) {
            this.stack2.push(this.stack1.pop())
        }
    }
    const stack2Len = this.stack2.length
    return stack2Len && this.stack2[stack2Len - 1]
}


MyQueue.prototype.empty = function () {
    return !this.stack1.length && !this.stack2.length
}