2012-09-26 93 views
0

我想在Java中的雙向鏈接列表上創建一個冒泡排序,但我得到空指針異常錯誤。我相信當我在head上調用getPrevious方法時會遇到問題,當然這個方法的值爲null。然而,我想不出如何在沒有訪問其他節點的getPrevious方法的情況下進行冒泡排序。泡沫排序雙向鏈接列表Java

我可以實現一個if語句來檢查它的頭部或尾部的第一個,但我覺得有一個更聰明的方法來做到這一點。

我也一直無法運行這個成功的構建,所以我甚至不知道代碼將工作。如果你對如何實現這個有不同的想法,請告訴我。

歡迎任何建議!

public static void bubbleSort(DoubleLinkedList list) //static method used to sort the linked list using bubble sort 
    { 
     int i = 0; 
     int j = 0; 
     Node currentNode = list.head; 
     Node previousNode = currentNode; 
     Node tempNext = currentNode; 
     Node tempPrevious = currentNode; 


     for(i=0; i<list.getSize(); i++) 
     { 
      for(j=0; j<list.getSize()-1; i++) 
      { 
       if(currentNode.getData() > currentNode.getNext().getData()) 
       { 
        tempNext = currentNode.getNext().getNext(); 
        tempPrevious = currentNode.getPrevious(); 
        currentNode.getPrevious().setNext(currentNode.getNext()); 
        currentNode.getNext().setNext(currentNode); 
        currentNode.setPrevious(currentNode.getNext()); 
        currentNode.setNext(tempNext); 

       } 

       currentNode = currentNode.getNext(); 

      } 
     } 



    } 

回答

2

所以你有一個雙鏈表。我假設每個元素都包含一些信息,比如一個整數。它還必須包含兩個指針:一個指向前一個元素,另一個指向下一個元素。

假設這是真的,請注意,您不必修改指針,因爲它們已經從一個元素指向另一個元素。您所要做的就是對列表元素的值進行排序,以便列表中的第一項具有最低值,第二項具有第二低值,依此類推。

你可以這樣說:

public static void bubbleSort(DoubleLinkedList list) //static method used to sort the linked list using bubble sort { 
     int i = 0; 
     Node currentNode = list.head; 
     Node auxNode; 
     int foundChange = 1; 
     while(foundChange) { 
     foundChange = 0; 
     for(i=0; i<list.getSize()-1; i++) { 
      if (currentNode.getData() > currentNode.getNext().getData()) { 
      auxNode.setData(currentNode.getData()); 
      currentNode.setData(currentNode.getNext.getData()); 
      currentNode.getNext.setData(auxNode.getData()); 
      foundChange = 1; 
      } 
      currentNode = currentNode.getNext(); 
     } 

} 

如果您還沒有定義SetData方法還沒有,那麼這樣做。它必須與getData類似,但它會將對象的數據設置爲它作爲參數獲取的值,而不是返回該對象中數據的值。

+0

我以前見過這個解決方案,但我不同意,並認爲這是可行的,如果節點會說... 3,4,5領域。 – Rabiees