JavaScript封裝優先級隊列

原文地址:JS優先隊列

另外:歡迎大家來我的個人網站 TanJia-前端技術分享

實現優先級隊列相對隊列主要考慮兩個地方:

  • 優先級隊列中每一個元素由元素的值與元素優先級組成
  • 添加元素時,要考慮到優先級。將新插入元素的優先級與隊列中已經存在的元素優先級進行比較,以獲得自己正確的位置

實現代碼如下:

<script type="text/javascript">
	function PriorityQueue(){
		/* 重新創建一個類 */
		function QueueElement(element,priority){
			this.element = element
			this.priority = priority
		}
		
		/* 封裝屬性 */
		this.items = []
		
		/* 實現插入方法 */
		PriorityQueue.prototype.enqueue = function(element,priority){
		     /* 1.創建QueueElement對象 */
			let queueElement = new QueueElement(element,priority)
			/* 2.判斷隊列是否爲空 */
			if(this.items.length === 0){
				this.items.push(queueElement)
			}else{
				var added = false
				for(let i=0;i<this.items.length;i++){
					if(queueElement.priority < this.items[i].priority){
						this.items.splice(i,0,queueElement)
						added = true
						break
					}
				}
				if(!added){
					this.items.push(queueElement)
				}
			}
		}
		/* 從隊列中刪除隊首的元素 */
		PriorityQueue.prototype.dequeue = function(){
			return this.items.shift()
		}
		/* 查看隊首元素 */
		PriorityQueue.prototype.front = function(){
			return this.items[0]
		}
		/* 查看隊列是否爲空 */
		PriorityQueue.prototype.isEmpty = function(){
			return this.items.length == 0 
		}
		/* 查看隊列的長度 */
		PriorityQueue.prototype.size = function(){
			return this.items.length
		}
		/* toString() */
		PriorityQueue.prototype.toString = function(){
			var resultString = ''
			for(var i=0; i<this.items.length; i++){
				resultString += this.items[i].element + '-'+ this.items[i].priority + ' '
			}
			return resultString
		}
	}
	var pq = new PriorityQueue()
	pq.enqueue('aaa',123)
	pq.enqueue('bbb',54)
	pq.enqueue('ccc',67)
	pq.enqueue('ddd',567)
	pq.enqueue('eee',90)
	console.log(pq.toString()) /*bbb-54 ccc-67 eee-90 aaa-123 ddd-567 */
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章