2014-03-06 41 views
0

我正在寫一個方法來切換鏈接列表中的一對值。切換鏈接列表中的值(處理節點)

例如,我的列表中包含:

1, 4, 5, 8, 9, 3 

的方法調用之後,該清單應包括:

4, 1, 8, 5, 3, 9 

處理鏈表是隻使用節點迷惑我,我不不明白爲什麼我的代碼只能切換列表中的前兩個值。有任何想法嗎?多一點解釋會很棒。謝謝。

public void switchPairs() { 
    ListNode current = front; 
    ListNode temp = front.next; 
    while(current.next != null) { 
        int i = front.data; 
     front.data = front.next.data; 
     front.next.data = i; 

        current = current.next; 
    } 
} 

回答

2

更改ListNode變量名firstsecond,它會更容易發現問題。您不能正確交換,也不能正確迭代ListNodes。你必須迭代2。

public void switchPairs() { 
    ListNode first = front;//first node in pair 
    ListNode second = front.next;//second node in pair 

    //while the both nodes are not null 
    while(first != null && second != null) { 
     int i = first.data;//put first value in temp value 
     first.data = second.data;//put second value in first node 
     second.data = i;//put temp value (first value) in second node 

     //NOTE: do some null pointer checks here just in case 
     first = second.next;//iterate first node 
     second = second.next.next;//iterate second node 
    } 
} 
+0

哦順便說一句,我認爲這隻適用於清單大小是奇數。 – JavaWannabee

1

這是因爲你沒有改變前面的值。所有的時間都在第一個和第二個數字之間改變。但是,由於電流設置爲最初前,每當當前值增加,直到它達到最後一個值