隊列和棧相似,都是對插入和刪除操作的部位做了限制特殊的線性表。在隊列中,只能從一頭刪除節點,這一頭叫做隊首;而另一端只能做插入操作,這一頭叫做隊尾。很容易理解,隊列是一個“先進先出”的線性表。隊列的應用有一個很常見的例子,就是打印機的作業隊列,打印機會維護一個作業隊列,先入隊的作業先執行~

同樣的,根據存儲結構的不同,隊列也有順序隊列和鏈式隊列兩種實現,代碼如下:
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;
}
}
