簡體   English   中英

如何使用無序鏈表實現優先級隊列

[英]How to implement priority queue with unordered linkedlist

我的想法是使用無序鏈表實現優先級隊列。

    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():

public Key delMax(){

    if(first==null) 
        return null;
    else if(n==1)
        return first.key;
    Node max=first,maxPrev=null,curr = max.next,prev = first;
    while(curr!=null){
        Key currMax = max.key;
        Key nextKey = curr.key;
        if(nextKey.compareTo(currMax)>0){
            max = curr;
            maxPrev = prev;
        }
        prev = curr;
        curr = curr.next;
    }
    if(maxPrev!=null)
        maxPrev.next=max.next;
    else
        first = max.next;
    n--;
    return max.key;
}

還修改以下內容:

int k = pq.n;
for(int j=0;j<k;j++){
    StdOut.print(pq.delMax());
    StdOut.println();
}

這應該返回您期望的this test is a輸出this test is a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM