Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript数据结构--队列(2018.01.03) #16

Open
aermin opened this issue Feb 13, 2018 · 0 comments
Open

javascript数据结构--队列(2018.01.03) #16

aermin opened this issue Feb 13, 2018 · 0 comments

Comments

@aermin
Copy link
Owner

aermin commented Feb 13, 2018

队列(Queue) ,和栈非常类似,但使用不用原则,即 先进先出 。
例子:排队
排队(队列),先进先出

创建队列
(和创建栈很类似,不详细讲,可参考javascript数据结构--栈

function Queue() {

    var items = [];
    //  队列尾部添加新项
    this.enqueue = function(element){
        items.push(element);
    };
     //移除并返回队列第一项
    this.dequeue = function(){
        return items.shift();
    };

    this.front = function(){
        return items[0];
    };

    this.isEmpty = function(){
        return items.length == 0;
    };

    this.clear = function(){
        items = [];
    };

    this.size = function(){
        return items.length;
    };

    this.print = function(){
        console.log(items.toString());
    };
}

Queue类和Stack类非常类似,唯一区别是dequeue 方法和front方法的不用,由先进先出,后进先出原则不同造成。

  • 使用
var queue = new Queue(); console.log(queue.isEmpty()); //؜true
queue.enqueue("John"); 
queue.enqueue("Jack");
queue.enqueue("Camila");
queue.print();//John,Jack,Camila
queue.dequeue(); 
queue.dequeue(); 
queue.print();//Camila

添加
删除

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant