24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
* Your algorithm should use only constant extra space.
* You may not modify the values in the list's nodes, only nodes itself may be changed.




https://www.youtube.com/watch?v=f45_eF1gmn8&t=68s




// correct 
class Solution {
    public ListNode swapPairs(ListNode head) {
     
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
    // ending condition 
        while(cur.next != null && cur.next.next != null){
            swap(cur);
            cur = cur.next.next;   
        }
        return dummy.next;
    }
    private void swap(ListNode cur){
        
        ListNode next1 = cur.next;
        cur.next = next1.next;
        next1.next = next1.next.next;
        cur.next.next = next1;
    }
}

 

posted on 2018-11-09 07:19  猪猪🐷  阅读(65)  评论(0)    收藏  举报

导航