24. Swap Nodes in Pairs

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

这题就是基本功。
先用dummyHead,
0 -> 1->2->3->4
先把 3那个点记往, 把2->3断开。
然后把2指向1,把1指向 3, 把0指向2

    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        ListNode node = dummy;
        dummy.next = head;
        while ( true ) {
            if (node == null || node.next == null || node.next.next == null) return dummy.next;
            ListNode next3 = node.next.next.next;
            node.next.next.next = null;
            ListNode next = node.next;
            ListNode next2 = next.next;
            node.next = next2;
            next2.next = next;
            next.next = next3;
            node = next;
        }
    }

你可能感兴趣的:(24. Swap Nodes in Pairs)