javascript中利用數組實現的迴圈隊列代碼

來源:互聯網
上載者:User

//迴圈隊列
function CircleQueue(size){
this.initQueue(size);
}
CircleQueue.prototype = {
//初始化隊列
initQueue : function(size){
this.size = size;
this.list = new Array();
this.capacity = size + 1;
this.head = 0;
this.tail = 0;
},
//壓入隊列
enterQueue : function(ele){
if(typeof ele == "undefined" || ele == ""){
return;
}
var pos = (this.tail + 1) % this.capacity;
if(pos == this.head){//判斷隊列是否已滿
return;
}else{
this.list[this.tail] = ele;
this.tail = pos;
}
},
//從隊列中取出頭部資料
delQueue : function(){
if(this.tail == this.head){ //判斷隊列是否為空白
return;
}else{
var ele = this.list[this.head];
this.head = (this.head + 1) % this.capacity;
return ele;
}
},
//查詢隊列中是否存在此元素,存在返回下標,不存在返回-1
find : function(ele){
var pos = this.head;
while(pos != this.tail){
if(this.list[pos] == ele){
return pos;
}else{
pos = (pos + 1) % this.capacity;
}
}
return -1;
},
//返回隊列中的元素個數
queueSize : function(){
return (this.tail - this.head + this.capacity) % this.capacity;
},
//清空隊列
clearQueue : function(){
this.head = 0;
this.tail = 0;
},
//判斷隊列是否為空白
isEmpty : function(){
if(this.head == this.tail){
return true;
}else{
return false;
}
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.