I need to implement a custom priority queue without using the PriorityQueue form Java.Util... I have three basic methods : insert, remove and clear . All operations must be done in constant time O (log n). How can I accomplish this ? What algorithms should I use for these operations ? And lastly, what type of container should I use in which to keep the generic values ?
This is what I've done so far ...
public class PriorityQueue<E extends Comparable<? super E>> implements Comparable {
private Stack<E> queue = new Stack<>();
private int size;
public PriorityQueue(int size) {
this.size = size;
}
public PriorityQueue() {
size = 50000;
}
public void insert(E value) {
if (value == null) {
throw new NullPointerException();
}
//how can I insert a value and what container should I use ?
}
public void remove() {
//remove largest
}
public int compareTo(Object o) {
if (o != null && o instanceof PriorityQueue) {
PriorityQueue anotherQueue = (PriorityQueue) o;
return this.size - anotherQueue.size;
} else {
throw new ClassCastException();
}
}
}
not much.. but help would be greatly appreciated !
I see your 'remove' operation takes the largest element. Seems like a 'Max Heap' would suit your purposes.
https://en.wikipedia.org/wiki/Heap_(data_structure)