Home  >  Article  >  Web Front-end  >  Circular queue code implemented using arrays in javascript_javascript skills

Circular queue code implemented using arrays in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:35:441087browse

//Circular Queue
function CircleQueue(size){
this.initQueue(size);
}
CircleQueue.prototype = {
//Initialization Queue
initQueue: function(size ){
this.size = size;
this.list = new Array();
this.capacity = size 1;
this.head = 0;
this.tail = 0 ;
},
//Push into queue
enterQueue: function(ele){
if(typeof ele == "undefined" || ele == ""){
return;
}
var pos = (this.tail 1) % this.capacity;
if(pos == this.head){//Determine whether the queue is full
return;
} else{
this.list[this.tail] = ele;
this.tail = pos;
}
},
//Get the head data from the queue
delQueue : function(){
if(this.tail == this.head){ // Determine whether the queue is empty
return;
}else{
var ele = this.list[this. head];
this.head = (this.head 1) % this.capacity;
return ele;
}
},
//Query whether this element exists in the queue, exists Return the subscript, if it does not exist, return -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;
},
//Return the number of elements in the queue
queueSize: function(){
return (this.tail - this.head this.capacity) % this.capacity;
} ,
//Clear the queue
clearQueue: function(){
this.head = 0;
this.tail = 0;
},
//Judge whether the queue is empty
isEmpty : function(){
if(this.head == this.tail){
return true;
}else{
return false;
}
}
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn