两两交换链表中的结点

两两交换链表中的结点

两个两个的交换链表中的结点,然后返回交换后的头节点

tips:

一般来说,这种操作可能会修改原始头节点,所以为了方便起见,我们最好使用一个哨兵结点去作为头节点,这样就不用去考虑额外的头节点。

解题

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode pCur = dummy;
        while (pCur != null && pCur.next != null && pCur.next.next != null) {
            ListNode p1 = pCur.next;
            ListNode p2 = pCur.next.next;
            pCur.next = p2;
            p1.next = p2.next;
            p2.next = p1;
            pCur = p1;
        }
        return dummy.next;
    }
}
Licensed under CC BY-NC-SA 4.0
花有重开日,人无再少年
使用 Hugo 构建
主题 StackJimmy 设计