1. 程式人生 > >資料結構之JavaScript實現佇列(queue)

資料結構之JavaScript實現佇列(queue)

    和棧一樣,佇列其實也是一種列表,不同的是佇列只能在隊尾插入元素,在隊首刪除元素,也就是說,佇列是先進先出的資料結構;而棧是先進後出的資料結構。佇列的主要操作就是入隊和出隊操作,也就是隊尾插入元素和隊首刪除元素。佇列還有一個比較重要的操作就是讀取隊首的元素。值得注意一點的是:優先佇列。優先佇列的普通佇列的不同是出隊的規則不同:普通佇列先進先出,就想排隊一樣;而優先佇列不一定先進先出,而是按照每個元素的優先順序來出隊。

JavaScript實現佇列程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>資料結構之JavaScript實現佇列</title>
</head>
<body>
	<script>
		function Queue(){
			this.dataStore = [];
			this.enqueue = enqueue;//入隊
			this.dequeue = dequeue;//出隊
			this.front = front;    //讀取隊首元素
			this.back = back;      //讀取隊尾元素
			this.empty = empty;
			this.length = length;
			this.clear = clear;
			this.toString = toString;
		}

		//入隊
		function enqueue(element){
		    this.dataStore.push(element);//在陣列末尾新增元素
		}

		//出隊
		function dequeue(){
			return this.dataStore.shift();//shift()刪除陣列第一個元素並返回
		}

		//讀取隊首元素
		function front(){
			return this.dataStore[0];
		}

		//讀取隊尾元素
		function back(){
			return this.dataStore[this.dataStore.length-1];
		}

		//判空
		function empty(){
			if(this.dataStore.length == 0){
				return true;
			}else{
				return false;
			}
		}

		//清空
		function clear(){
			this.dataStore = [];
		}

		//返回佇列長度
		function length(){
			return this.dataStore.length;
		}

		//toString
		function toString(){
			return this.dataStore;
		}

		var que = new Queue();
		que.enqueue(1);
		que.enqueue(2);
	</script>
</body>
</html>
下面是優先佇列的出隊操作,其他操作都相同。
	//優先佇列:其實只是出隊時有點不同,優先佇列不一定是先進先出,而是按照對內元素的優先順序出隊。
	/*假設現在佇列內的元素是一個物件,有一個code屬性表示其優先順序,數字越小優先順序有越高*/
	function previligedequeue(){
	    var entry = 0;
	    for(var i=0;i<this.dataStore.length;i++){
	    	if(this.dataStore[i].code<this.dataStore[entry].code){
	    		entry = i;
	    	}
	    }
	    return this.dataStore.splice(entry,1);
	}