队列和栈相似,都是对插入和删除操作的部位做了限制特殊的线性表。在队列中,只能从一头删除节点,这一头叫做队首;而另一端只能做插入操作,这一头叫做队尾。很容易理解,队列是一个“先进先出”的线性表。队列的应用有一个很常见的例子,就是打印机的作业队列,打印机会维护一个作业队列,先入队的作业先执行~
同样的,根据存储结构的不同,队列也有顺序队列和链式队列两种实现,代码如下:
function LinkedQueue () {
//节点结构定义
var Node = function(element){
this.element = element;
this.next = null;
} var length = 0,
front,//队首指针
rear;//队尾指针
//入队操作
this.push = function(element){
var node = new Node(element),
current;if(length == 0){
front = node;
rear = node;
length++;return true;
}else{
current = rear;
current.next = node;
rear = node;
length++;return true;
}
}
//出队操作
this.pop = function(){
if(!front){
return 'Queue is null';
}else{
var current = front;
front = current.next;
current.next = null;
length--;
return current;
}
}
//获取队长
this.size = function(){
return length;
}
//获取队首
this.getFront = function(){
return front;
}
//获取队尾
this.getRear = function(){
return rear;
}this.toString = function(){
var str = '',
current = front;while(current){
str += current.element;
current = current.next;
}return str;
}
//清除队列
this.clear = function(){
front = null;
rear = null;
length = 0;
return true;
}
}function ArrayQueue(){
var arr = [];
//入队操作
this.push = function(element){
arr.push(element);
return true;
}
//出队操作
this.pop = function(){
return arr.shift();
}
//获取队首
this.getFront = function(){
return arr[0];
}
//获取队尾
this.getRear = function(){
return arr[arr.length - 1]
}
//清空队列
this.clear = function(){
arr = [];
}
//获取队长
this.size = function(){
return length;
}
}