Why I have to use prev = prev.next.next ?


  • 0
    S

    I tried to solve this problem and finally got one kind of solution as below:

    public ListNode swapPairs(ListNode head) {
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode prev = dummy;
            
            while(prev.next != null && prev.next.next != null) {
                ListNode first = prev.next;
                ListNode second = prev.next.next;
                first.next = second.next;
                prev.next = second;
                second.next = first;
                prev = prev.next.next;          
            }
            return dummy.next;
        }
    

    But I am wondering why I can't use the following statement as below? I think now prev.next.next and first refer to the same position. But when I change to prev = first in the while loop, the code cannot be run correctly. Can anybody tell me the reason?

    public ListNode swapPairs(ListNode head) {
                ListNode dummy = new ListNode(-1);
                dummy.next = head;
                ListNode prev = dummy;
                
                while(prev.next != null && prev.next.next != null) {
                    ListNode first = prev.next;
                    ListNode second = prev.next.next;
                    first.next = second.next;
                    prev.next = second;
                    second.next = first;
                    //prev = prev.next.next;  
                    prev = first;
                }
                return dummy.next;
            }

  • 0
    T

    Your solution is same to mine. Because after one loop,the next two node(after the prev) will have already been swaped. So u need to make the prev move to its next and next node! But the first(vari name) presents the next node of prev, if u make prev= first , the swap will happen again.For example,
    -1->1->2->3->4; After the first loop, the list will be -1->2->1->3->4; so the prev must direct to 3 not 2. Am i clear?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.