# O

xamples

epeat

ode

pproach

ptimize

est

### Breakdown

1. Define the structure of the priority queue
2. Define the insert function
3. Define the peek and popMax functions

### 1. Define the Priority Queue

``````
function Node(data, priority) {
this.data = data;
this.priority = priority;
this.next;
}

function PriorityQueue() {
this.first;
}``````

### 2. Define the insert function

``````
PriorityQueue.prototype.insert = function(data, priority) {
if (!this.first || this.first.priority < priority) {
// First case handles both empty PQ and higher priority than anything else
var prevFirst = this.first;
this.first = new Node(data, priority);
this.first.next = prevFirst;
} else {
// Second case finds the place to insert the new item and inserts it
var pointer = this.first;
while (pointer.next && pointer.next.priority >= priority) {
pointer = pointer.next;
}
var newItem = new Node(data, priority);
newItem.next = pointer.next;
pointer.next = newItem;
}
}
``````

### 3. Define the peek and popMax functions

``````
PriorityQueue.prototype.peek = function() {
return this.first.data;
}

PriorityQueue.prototype.popMax = function() {
var retVal = this.first.data;
this.first = this.first.next;
return retVal;
}``````

### Performance

How fast is each function?

insert

O(n) - takes time proportional to the number of items in the priority queue

peek

O(1) - you always have a reference to the max element

popMax

O(1) - you always have a reference to the max element

### Conclusion

The other way to do this would be to just insert the new elements at the front and search for the highest whenever you need it.  (Overall this is slower since you'd be searching for its location once when you use popMax plus every time you peek rather than just once when you insert)

By gtelljohann

• 1,838