js隊列的實現問題


所謂隊列就是排隊的序列問題,有出有進,比如在銀行排隊辦理業務,一般都是前一個辦理完成后下一個自動進入隊列

<script>  /*

 * 模擬隊列

 */

var Qu ={};

 

//構造函數

Qu.Queue = function (len) {

    this.capacity = len;        //隊列最大容量

    this.list = new Array();    //隊列數據

};

 

//入隊

Qu.Queue.prototype.enqueue = function (data) {

    if (data == null) return;

    if(this.list.length>=this.capacity)

    {

        this.list.remove(0);

    }

    this.list.push(data);

};

 

//出隊

Qu.Queue.prototype.dequeue = function () {

    if (this.list == null) return;

    this.list.remove(0);

};

 

//隊列長度

Qu.Queue.prototype.size = function () {

    if (this == null) return;

    return this.list.length;

};

 

//隊列是否空

Qu.Queue.prototype.isEmpty = function () {

    if (this == null|this.list==null) return false;

    return this.list.length>0;

};

 

//對象數組擴展remove

Array.prototype.remove = function(dx) {

    if (isNaN(dx) || dx > this.length) {

        return false;

    }

    for (var i = 0, n = 0; i < this.length; i++) {

        if (this[i] != this[dx]) {

            this[n++] = this[i]

        }

    }

    this.length -= 1

}

  

調用例子:

//隊列初始化

var queue = new Qu.Queue(10);

queue.enqueue(1);

queue.enqueue(2);

queue.enqueue(3); </script>

/*

 * 模擬隊列

 */

var Qu ={};

 

//構造函數

Qu.Queue = function (len) {

    this.capacity = len;        //隊列最大容量

    this.list = new Array();    //隊列數據

};

 

//入隊

Qu.Queue.prototype.enqueue = function (data) {

    if (data == null) return;

    if(this.list.length>=this.capacity)

    {

        this.list.remove(0);

    }

    this.list.push(data);

};

 

//出隊

Qu.Queue.prototype.dequeue = function () {

    if (this.list == null) return;

    this.list.remove(0);

};

 

//隊列長度

Qu.Queue.prototype.size = function () {

    if (this == null) return;

    return this.list.length;

};

 

//隊列是否空

Qu.Queue.prototype.isEmpty = function () {

    if (this == null|this.list==null) return false;

    return this.list.length>0;

};

 

?

//對象數組擴展remove

Array.prototype.remove = function(dx) {

    if (isNaN(dx) || dx > this.length) {

        return false;

    }

    for (var i = 0, n = 0; i < this.length; i++) {

        if (this[i] != this[dx]) {

            this[n++] = this[i]

        }

    }

    this.length -= 1

}

  

調用例子:

//隊列初始化

var queue = new Qu.Queue(10);

queue.enqueue(1);

queue.enqueue(2);

queue.enqueue(3);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM