2014-03-06 2 views
0

링크 된 목록에서 한 쌍의 값을 전환하는 방법을 쓰고 있습니다.링크 된 목록의 값 전환 (노드 다루기)

예를 들어, 내 목록에 포함

4, 1, 8, 5, 3, 9 

만 노드를 사용하여 저를 혼란 연결리스트를 처리하고, 내가 돈 :

1, 4, 5, 8, 9, 3 

메서드 호출 후, 목록이해야 포함 왜 내 코드가 목록의 처음 두 값만 전환하는지 이해할 수 없습니다. 어떤 아이디어? 조금 더 설명하면 좋을 것입니다. 고맙습니다.

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
firstsecondListNode 변수 이름을 변경

, 문제를 발견하기 쉬울 것입니다. 제대로 교환하지 않았거나 올바르게 수행하지 마십시오. ListNodes. 두 값을 모두 반올림해야합니다.

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

오 btw, 이것은 목록 크기가 이상한 경우에만 작동한다고 생각합니다. – JavaWannabee

1

이는 앞 값을 변경하지 않기 때문입니다. 항상 앞 번호가 첫 번째 숫자와 두 번째 숫자 사이에서 변경됩니다. 그러나 전류가 처음에는 정면으로 설정되기 때문에 현재 값이 마지막 값에 도달 할 때까지 현재 값이 증가 할 때마다