隊列的JS實現

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


        一樣的,根據存儲結構的不一樣,隊列也有順序隊列和鏈式隊列兩種實現,代碼以下:java

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;
	}
}
相關文章
相關標籤/搜索