2013-04-13 42 views
1
protected void sortHorseList(int iHorseCount) 
{ 
    int i = 0; 
    Horsie currentNode = head; 
    Horsie auxNode = new Horsie(); 
    boolean foundChange = true; 
    while(foundChange) 
    { 
     foundChange = false; 
     for(i=0; i<iHorseCount-1; i++) 
     { 
      if (currentNode.getHorseValue() > currentNode.getNext().getHorseValue()) 
      { 
       auxNode.setHorseValue(currentNode.getHorseValue()); 
       currentNode.setHorseValue(currentNode.getNext().getHorseValue()); 
       currentNode.getNext().setHorseValue(auxNode.getHorseValue()); 
       foundChange = true; 
      } 
      currentNode = currentNode.getNext(); 
     } 
    } 
} 

此代碼顯示運行主程序時,空指針錯誤。我是數據結構的新手,我希望能夠幫助你解決這個問題!請教我如何使用冒泡排序雙向鏈表 ... HEEELP!冒泡排序的雙向鏈表 - 空指針錯誤

+0

請用相關編程語言標記。 –

+0

哪行引發NullPointerException? – RyPope

+0

作業?沒有人對鏈接列表進行排序,也沒有人使用學術界以外的冒泡排序。 – EJP

回答

1

當您到達列表的末尾時,您不檢查是否存在下一個元素。因此當你試圖訪問它的值時,你會得到空引用異常。你的內循環應該是這個樣子

Horsie currentNode = head; 
    Horsie nextNode = currentNode != null ? currentNode.getNext() : null; 
    while (currentNode != null && nextNode != null) 
    { 
     if (currentNode.getHorseValue() > nextNode.getHorseValue()) 
     { 
      currentNode = Swap(head,currentNode,nextNode); 
      foundChange = true; 
     } 
     else 
     { 
      currentNode = nextNode; 
     } 
     nextNode = currentNode.getNext(); 
    } 

Swap(Horsie current, Horsie next)交流的列表currentnext的地方和可選更新目若current是頭節點。

我還會注意到你想要交換列表中的節點,而不是交換節點之間的值,除非您確定您的列表只包含對節點對象的唯一引用。如果你不這樣做,你會冒着讓某個其他類的對象意外變異的風險,因爲在排序過程中你已經改變了它的值。

+0

你能幫我用Swap方法嗎?我怎樣才能開始這個方法? –

+0

@VincentSy - 你只需要修正(轉發)指針,使得current的父指向next,next指向current,current指向next的previous追隨者。與後面的指針類似。您還需要處理'current'是'head'元素以及'next'是尾部的特殊情況。 – tvanfosson

+0

我該怎麼辦?你可以給我代碼嗎? (BEGINNER):\ –