Changing a LinkedList into a Priority Queue
I currently have a class that has 3 linkedlists of strings or ints that I use as a stack via a trio of addFirst
and removeFirst
commands. (Class reproduced below)
I want to add the ability to use the class as a priority queue instead. I know what a priority queue is, so I'm looking for a simple way to add insertWithPriority
and removeNext
.
The intuitive option is to switch from a class of 3 linkedLists to 3 priorityQueues instead, but I'm a little confused how to use the priority queues in java. Specifically, I need priority for all 3 to function identically such that removeNext will remove the same 3 elements that were added by insertWithPriority
.
Could someone shed some light on how to implement a proper priorityQueue?
class ThreeList{
public LinkedList foo;
public LinkedList bar;
public LinkedList etal;
public ThreeList(){
foo= new LinkedList();
bar= new LinkedList();
etal= new LinkedList();
}
public void addLast(String foo, int bar, int etal){
foo.addLast(foo);
bar.addLast(bar);
etal.addLast(etal);
}
public void addFirst(String foo, int bar, int etal){
foo.addFirs开发者_C百科t(foo);
bar.addFirst(bar);
etal.addFirst(etal);
}
public void removeFirst(){
foo.removeFirst();
bar.removeFirst();
etal.removeFirst();
}
public void removeLast(){
foo.removeLast();
bar.removeLast();
etal.removeLast();
}
}
PriorityQueue
offers priorization by use of Comparable or Comparator, i.e. you only use add.
In your case it would be best to use a simple static inner class to capture foo, bar and etal into one object.
static class FooBar implements Comparable<FooBar> {
String foo;
int bar, etal;
int compareTo(FooBar other) {
... comparison logic here...
}
}
If the values foo,bar,etal don't implicitly contain a priority, you need to add another field to FooBar and use that in compareTo
.
精彩评论