18888628835/Blog

队列

18888628835 opened this issue · 0 comments

队列

队列(Queue)介绍

队列的结构跟栈相反,队列是先进先出的数据结构。

队列基本操作有两种:入队和出队。从队列的后端位置添加实体,称为入队;从队列的前端位置移除实体,称为出队。

对应的 API 为 Array.prototype.push 和Array.prototype.shift方法。

当出队列时,即调用 shift 方法时,由于所有后排的数据都要往前推一格,所以出队列时的时间复杂度为 O(n)

下图为队列中元素先进先出 FIFO (first in, first out)的示意
image

用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
 

注意:

你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
 

示例:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
 

提示:

1 <= x <= 9
最多调用100 次 push、pop、top 和 empty
每次调用 pop 和 top 都保证栈不为空

答案

var MyStack = function() {
    this.queue=[]
    this._queue=[]
};

MyStack.prototype.push = function(x) {
    //直接 push 即可
    this.queue.push(x)
};

MyStack.prototype.pop = function() {
    //把主队列的元素除了最后一个外都shift出来 push 进副队列
    while(this.queue.length>1){
        this._queue.push(this.queue.shift())
    }
    //剩下的 这个就是要返回的 pop 的元素
    const num=this.queue.shift()
    // 记下 pop 出去的元素后记得把副队列的元素 push 回主队列
    while(this._queue.length){
        this.queue.push(this._queue.shift());
    }
    return num
};

MyStack.prototype.top = function() {
    //队列的顶就是队列的最后一个元素
    return this.queue[this.queue.length-1]
};

MyStack.prototype.empty = function() {
    //没啥好说的
    return this.queue.length===0
};