刚刚用LinkedList
. 我知道这是一个初学者的实现。肯定有很多错误。我只想知道是否有人可以告诉我该insert(K key, V value)
方法最坏情况的成本。我应该留在 O(n) 吗?
addLast()
使用和中的getLast()
方法进行编辑,LinkedList
并使用ListIterator
而不是Iterator
.
公共类 SortedListPriorityQueue 实现 PriorityQueue {
protected List<Entry<K,V>> entries;
protected Comparator<K> c;
private static class MyEntry<K,V> implements Entry<K,V>{
protected K key;
protected V value;
public MyEntry(K key, V value){
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return this.key;
}
@Override
public V getValue() {
return this.value;
}
}
/**
* Crea la coda con il comparatore DefaultComparator
*/
public SortedListPriorityQueue() {
entries = new LinkedList<Entry<K,V>>();
c = new DefaultComparator<K>();
}
/* Utilizza un comparatore specifico
public SortedListPriorityQueue(Comparator<K> comp) {}
*/
@Override
public int size() {
return entries.size();
}
@Override
public boolean isEmpty() {
return entries.isEmpty();
}
@Override
public Entry<K, V> min() {
if(entries.isEmpty()) throw new RuntimeException("Priority queue is empty");
else return entries.get(0);
}
@Override
public Entry<K, V> removeMin() {
if(entries.isEmpty()) throw new RuntimeException("Priority queue is empty");
else return entries.remove(0);
}
@Override
public Entry<K, V> insert(K key, V value) {
Entry<K,V> new_entry = new MyEntry<K,V>(key, value);
insertEntry(new_entry);
return new_entry;
}
private void insertEntry(Entry<K, V> e) {
//caso base1: lista vuota
if(entries.isEmpty()){
entries.add(e);
return;
}
// caso base2: inserisce alla fine della lista
else if(c.compare(e.getKey(), ((LinkedList<Entry<K, V>>) entries).getLast().getKey()) > 0){
((LinkedList<Entry<K,V>>) entries).addLast(e);
return;
}
ListIterator<Entry<K,V>> it = entries.listIterator();
Entry<K,V> current = null;
while(it.hasNext()){
current = it.next();
if(c.compare(e.getKey(), current.getKey()) < 0){
it.add(e);
return;
}
}
}
}