優先度キューをの順序なしリンクリストで実装する考えがあります。順序付けされていないリンクリストで優先度キューを実装する方法
public class UnorderedLinkedListMaxPQ<Key extends Comparable<Key>> {
private Node first;
private int n; //number of elements
private class Node{
Key key; //elements
Node next;
}
public boolean isEmpty() {return first==null;}
public int size() {return n;}
public void insert(Key key){
Node oldfirst=first;
first=new Node();
first.key=key;
first.next=oldfirst;
n++;
}
public Key delMax(){
Node node=first;
if(node==null) {return null;}
Key max=node.key;
while(node.next!=null){
Key data=node.next.key;
if(data.compareTo(max)>0){
max=data;
}
node=node.next;
}
first=first.next;
n--;
return max;
}
//Test Routine
public static void main(String[] args) {
UnorderedLInkedListMaxPQ<String> pq=new UnorderedLInkedListMaxPQ<String>();
pq.insert("this");
pq.insert("is");
pq.insert("a");
pq.insert("test");
for(int j=0;j<pq.n;j++){
StdOut.print(pq.delMax());
StdOut.println();
}
}
}
リンクリストのmax要素を検索し、maxest要素を返します。 しかし、私がテストすると、this this
の出力はthis test is a
となります。
私の道具に何か問題がありますか?何か提案がありますか?
あなたのdelMaxでは、あなたは最大を削除していません、あなたが最初に削除されています。 –
最悪の可能性のあるパフォーマンスでこれをやっているのはなぜですか? – Andreas
データに注文する必要があることが分かっている場合は、注文してください。 – ChiefTwoPencils