24. [M] Swap Nodes in Pairs

https://leetcode.com/problems/swap-nodes-in-pairs/

类似 206 反转列表。只是在过程处理上略有区别。

使用四个指针,分别记录前一个节点 p ,当前节点对 c1 c2 ,和后一个节点 n 。根据逻辑,分别更新 c1, c2 的指向,然后移动 p 和 c1 。

初始          :  (p) (1/c1) -> (2/c2) -> (3/n) -> (4)
更新 c1 -> n  :  (p) (1/c1) -> (3/n) -> (4) 
更新 c2 -> c1 :  (p) (2/c2) -> (1/c1) -> (3/n) -> (4) 
更新 p -> c2  :  (p) -> (2/c2) -> (1/c1) -> (3/n) -> (4) 
更新 p, c1    :  (2) -> (1/p) -> (3/c1) -> (4/c2) 

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        // (p) (1/c1) -> (2/c2) -> (3/n) -> (4)
        ListNode p = null, c1 = head, c2 = null, n = null;
        head = c1.next;
        while (c1 != null && c1.next != null) {
            c2 = c1.next;
            n = c2.next;
            
            c1.next = n;
            c2.next = c1;
            if (p != null) {
                p.next = c2;
            }
            p = c1;
            c1 = n;
        }
        return head;
    }
}

最后更新于

这有帮助吗?