2014-03-06 39 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

这是因为你没有改变前面的值。所有的时间都在第一个和第二个数字之间改变。但是,由于电流设置为最初前,每当当前值增加,直到它达到最后一个值