JavaScript Data structure-priority Queue

Source: Internet
Author: User

The reason for the expansion of a limited queue is that the queues in life are usually attached with priority, such as queuing up for tickets, the general elderly and the military will have a priority limit.

Implementation: inherit the normal queue implementation of the previous Article. Here in a way, when the queue, the order is inserted into the specified position, the output is Unchanged.

Priority Queue Class
Inherit from Queuefunction priorityqueue () {queue.call (this);}

  

Inheriting the prototype method
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);

  

Add data
Add a node class function node (element, priority) {this.element = element;this.priority = priority;} Update Add PriorityQueue.prototype.enqueue = function (element, priority) {var node = new node (element, priority); 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);}}}

  

Full code
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)}

The following list of research links

JavaScript Data structure-priority Queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.