2013-03-15 52 views
1

我一直在搞這一段時間,似乎不管我做什麼,我的輸出總是被截斷或「任意排序」。移動引用足以交換兩個元素嗎?我試圖做到這一點,如果當前節點的SSN字段大於前一個字段,請將前一個字段與當前字段鏈接。這是我的代碼看起來此刻:如何在建立的單向鏈表中交換兩個節點?

public void loadRecords() throws FileNotFoundException { 

    Node head = null; 
    Node prev = null; 
    Node curr = null; 
    Scanner fileRead = makeAFile(database); 
    fileRead.useDelimiter(";|\n"); 
    boolean sorted = false; 
    while (fileRead.hasNext()) { 
     head = new Node(fileRead.next(), fileRead.next(), fileRead.next()); 
     head.nextOne = prev; 

     if (prev != null) { 
      for (curr = head; curr != null; curr = curr.nextOne) { 
       if ((curr).compareTo(prev) > 0) { 

        head.nextOne = prev.nextOne; //oops, there we go. used to be "head.nextOne = curr.nextOne". 
        prev = head; // not even sure if this is what I want 
        sorted = true; 
       } else 
        break; 
      } 
     } 

     if (sorted != true) { 
      prev = head; 
     } 
     sorted = false; 
    } 
} 

回答

0

您可能需要像這樣

   Node tmp = head.nextOne 
       head.nextOne = prev.nextOne; 
       prev.nextOne = tmp;