2012-09-26 4 views
0

Java에서 이중 연결 링크 목록에 버블 정렬을 만들려고하지만 Null 포인터 예외 오류가 발생합니다. 나는 그것이 null 값을 가지고있는 머리에 getPrevious 메소드를 호출 할 때 문제가 있다고 생각한다. 그러나 다른 노드에 대한 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

그래서 이중 연결 목록이 있습니다. 각 요소에 몇 가지 정보가 포함되어 있다고 가정합니다. 정수를 말합니다. 또한 이전 요소에 하나, 다음 요소에 하나씩 두 개의 포인터가 있어야합니다.

사실이라고 가정하면 포인터가 이미 한 요소를 가리 키므로 포인터를 수정할 필요가 없습니다. 목록의 첫 번째 항목이 가장 낮은 값을 가지며 두 번째 항목이 두 번째로 낮은 값을 갖도록 목록 요소의 값을 정렬하기 만하면됩니다.

당신은 이런 식으로 작업을 수행 할 수 있습니다 아직 사항 setData 방법을 정의하지 않은 경우,이를

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(); 
     } 

} 

. getData와 유사해야하지만 객체의 데이터 값을 반환하는 대신 매개 변수로 가져 오는 값으로 객체의 데이터를 설정합니다.

+0

이전에이 솔루션을 보았지만 Node가 3,4,5 개의 필드를 사용하면 가능하다고 생각하지 않습니다. – Rabiees