This repository was archived by the owner on Dec 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.java
More file actions
53 lines (46 loc) · 1.4 KB
/
PriorityQueue.java
File metadata and controls
53 lines (46 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.Comparator;
/* This class is a sorted LinkedList. It stores the data in a specialised structure i.e., Pair.
* This Pair contains two things: the priority of the object (an integer) and the object itself.
* When inserting a new element in the PriorityQueue the LinkedList is traversed.
* When an element is found with a lower priority then the new object is stored in front of it.
* Author: Seppe Lampe
*/
public class PriorityQueue
{
public class Pair implements Comparable
{
public Object element;
public int priority;
public Pair(Object element , int priority) {
this.element = element;
this.priority = priority;
}
public int compareTo(Object o) { //O(1)
Pair p2 = (Pair)o;
return ((Comparable)priority).compareTo(p2.priority);
}
}
private LinkedList data;
public PriorityQueue()
{
data = new LinkedList();
}
// Add a new element with a certain priority to the PriorityQueue
public void push(Object o, int priority) //O(n)
{
Pair newPair = new Pair(o, priority);
data.addSorted(newPair);
}
// Remove the element with the highest priority and return it
public Object pop() //O(1)
{
Object storage = data.getFirst();
data.removeFirst();
return storage;
}
// Show the element with the highest priority
public Object top() //O(1)
{
return data.getFirst();
}
}