JS-栈、队列

栈、队列

栈是一种数据结构(后进先出), 也就是说最新添加的元素最早被移除。而栈中元素的插入(或叫推入)和移除(或叫弹出),只发生在一个位置——栈的顶部。 ECMAScript 为数组专门提供了 push()和 pop()方法。

  • push()----可以传入任意数量的参数,把他们逐个添加到数组的末尾(栈顶);
  • pop()----从数组末尾(栈顶)移除最后一个元素,减少数组的 length 值,并返回移除的元素。

队列方法是先进先出。 列队在数组的末端添加元素, 从数组的
前端移除元素。

  • push()向数组末端加一个元素,
  • shift()方法从数组前端移除一个元素

用两个栈实现一个队列

对应 剑指offer 09
思想:
1、栈一只用来添加元素,栈二只用作弹出元素
2、添加元素直接将元素push进栈一
3、弹出元素时,首先判断栈二是否为空,不为空直接pop出一个元素,否则将栈一中所有元素依次压入栈二,在pop出一个元素。

var CQueue = function () {
    this.stack1 = [];
    this.stack2 = [];
}
CQueue.prototype.appendItem = function (value) {
    this.stack1.push(value);
}
CQueue.prototype.deleteItem = function (value) {
    if (!this.stack2.length) {
        while (this.stack1.length) {
            this.stack2.push(this.stack1.pop());
        }
    }
    return this.stack2.pop() || -1;
}
// var queue = new CQueue();
// queue.appendItem('1');
// queue.appendItem('2');
// queue.appendItem('3');
// console.dir(queue);

用两个队列实现一个栈

思想:
1、压入元素,在不为空的队列中压入元素,两队列都为空则随便压入其中一个,这里假设在队2中压入元素。
2、弹出元素,将不为空的队列中(假设队2),除队尾最后一个元素,其余元素依次插入另一队列(队1),并将队2最后一个元素在队头shift出来。
3、弹出元素时,若不为空队列中只有一个元素,则直接将该元素shift出来。

var CStack = function () {
    this.queue1 = [];
    this.queue2 = [];
}
CStack.prototype.appendItem = function (value) {
    this.queue1.length == 0 ? this.queue2.push(value) : this.queue1.push(value);
}
CStack.prototype.deleteItem = function () {
    if (!this.queue1.length) {
        if (this.queue2.length === 1) {
            return this.queue2.shift();
        }
        while (this.queue2.length > 1) {
            this.queue1.push(this.queue2.shift());
        }
        return this.queue2.shift() || -1;    
        
        
    } else {
        if (this.queue1.length === 1) {
            return  this.queue1.shift();
        }
        while (this.queue1.length > 1) {
            this.queue2.push(this.queue1.shift())
        }
        return this.queue1.shift() || -1;
    }
}
//var stack = new CStack();
//stack.appendItem('1');
//stack.appendItem('2');
//stack.appendItem('3');
//console.dir(stack);
posted @ 2020-06-30 13:38  精灵W的博客  阅读(141)  评论(0编辑  收藏  举报