javascript資料結構-優先隊列

來源:互聯網
上載者:User

標籤:script   data   node   nbsp   sem   隊列實現   原型   位置   prot   

 

這裡之所以擴充一個 有限隊列 是因為,生活使用中隊列通常會附加優先順序,比如排隊買票,一般老人和軍人等會有優先許可權。

實現:繼承上篇的 普通隊列實現。這裡用一種方法,入隊的時候,進行排序插入到指定位置,輸出不變。

優先隊列類
//繼承自 Queuefunction PriorityQueue(){Queue.call(this);}

  

繼承原型方法
function base(p, c){var h = {}, P = p.prototype, C = c.prototype;for(var k in C){h[k] = 1;}for(var k in P){if(!h[k]){C[k] = P[k];}}}base(Queue, PriorityQueue);

  

添加資料
// 增加一個節點類function Node(element, priority){this.element = element;this.priority = priority;}// 更新添加PriorityQueue.prototype.enqueue = function (element, priority){var node = new Node(element, priority);if(this.isEmpty()){this.data.push(node);}else{var add = false;for(var i = 0,len=this.data.length; i<len; i++){if(node.priority < this.data[i].priority){this.data.splice(i, 0, node);add = true;break;}}if(!add){this.data.push(node);}}}

  

完整代碼
function PriorityQueue(){Queue.call(this);}function base(p, c){var h = {}, P = p.prototype, C = c.prototype;for(var k in C){h[k] = 1;}for(var k in P){if(!h[k]){C[k] = P[k];}}}base(Queue, PriorityQueue);function Node(element, priority){this.element = element;this.priority = priority;}PriorityQueue.prototype.enqueue = function (element, priority){var node = new Node(element, priority);if(this.isEmpty()){this.data.push(node);}else{var add = false;for(var i = 0,len=this.data.length; i<len; i++){if(node.priority < this.data[i].priority){this.data.splice(i, 0, node);add = true;break;}}if(!add){this.data.push(node);}}}PriorityQueue.prototype.print = function (){console.dir(this.data)}

  下面研究鏈表

javascript資料結構-優先隊列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.