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;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容