2011-05-16 70 views
1

我正在處理一個旅行推銷員問題,而我的p隊列沒有運行,只是簡單地添加了最後一個項目。我想知道是否有人能幫我弄清楚錯誤。這裏是我的節點類(節點被添加到隊列):需要Java優先隊列幫助

import java.util.*; 

public class Node implements Comparable<Node>{ 

    //level of node 
    int level; 
    //stores path of node 
    ArrayList<Integer> path = new ArrayList<Integer>(); 
    //bound of node 
    int bound; 

    /** Over-rides compareTo for priority queue handling 
     * @return int desired sorting value 
     */ 
    public int compareTo(Node aNode) 
    {    
     if (this.bound<aNode.bound) 
     { 
      return 1; 
     } 
     if (this.bound>aNode.bound) 
     { 
      return -1; 
     } 
     else 
     { 
      return 0; 
     } 
    } 
} 

,這裏是p型隊列實現:

PriorityQueue<Node> theQ = new PriorityQueue<Node>(); 

的算法是正確實施對隊列根本不把最低限度作爲頭。我甚至將compareTo的回報調整爲對p-隊列輸出沒有任何影響(這意味着隊列沒有排序,我浪費了數小時的時間試圖找出它,並且還要求一些同學(沒有人能夠辨別出問題)採取了在這裏拍攝,看是否有人知道爲什麼排隊充當這樣的..

+0

定義 「P-隊列輸出」 ......你的意思,如果你通過迭代該隊列不符合您的期望?你如何進入隊列? – 2011-05-16 04:40:29

+0

是我投票的q和它輸出的最後一個項目添加,其不排序... – idkWATimDOIN 2011-05-16 04:41:37

+1

它會很有幫助,如果你發佈的代碼,你在訪問隊列 – 2011-05-16 04:50:39

回答

3

您的代碼工作完全正常,我。

我懷疑你正在做的是改變單個對象的值bound並重復添加它,給你一個充滿同一個對象的隊列(大量引用它),當然這個對象有單個對象)值你設置它。

public static void main(String[] args) 
{ 
    PriorityQueue<Node> theQ = new PriorityQueue<Node>(); 
    Node n = new Node(); 
    n.bound = 6; 
    theQ.add(n); 
    n = new Node(); 
    n.bound = 9; 
    theQ.add(n); 
    n = new Node(); 
    n.bound = 4; 
    theQ.add(n); 
    while ((n = theQ.poll()) != null) 
     System.out.println("Bound = " + n.bound); 
} 

輸出:

束縛= 9
束縛= 6
束縛= 4

+0

你釘了它的先生,我宣佈我的新節點在必要的循環之外,你的救星!非常感謝你 – idkWATimDOIN 2011-05-16 05:01:01

2

確保您通過PriorityQueue迭代通過使用由Queue接口,前提供的方法。remove流行元素關閉頂在僞代碼:

for each element in some other collection 
    priorityQueue.add(element) 

while priorityQueue is not empty 
Set node to priorityQueue.remove() 
Do stuff with node 

如果您正試圖通過for-each循環或PriorityQueue.iterator遍歷:

在方法中提供 迭代器()的迭代器並不保證 遍歷優先 隊列的任何特定順序的元素。

另外,如果你不想毀掉/從你的PriorityQueue刪除元素,以迭代,你可以使用,如文檔建議,

Arrays.sort(pq.toArray()) 
+0

已經問他,請參閱下面的問題的意見。 – 2011-05-16 04:52:25