1. 程式人生 > 其它 >LeetCode 0024 Swap Nodes in Pairs

LeetCode 0024 Swap Nodes in Pairs

原題傳送門

1. 題目描述

2. Solution 1

1、思路分析
每次反轉兩個結點,head 與 suc = head.next,然後遞迴處理後續結點。
2、程式碼實現

package Q0099.Q0024SwapNodesInPairs;

import DataStructure.ListNode;

public class Solution1 {
    /*
      recursion
     */
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode suc = head.next;
        head.next = swapPairs(suc.next);
        suc.next = head;
        return suc;
    }
}

3. Solution 2

1、思路分析
迭代, 後繼: successor , pre->cur->suc->rear ==> pre->suc->cur->rear
2、程式碼實現

package Q0099.Q0024SwapNodesInPairs;

import DataStructure.ListNode;

public class Solution2 {
    /*
      iteration
      後繼: successor
      pre->cur->suc->rear ==> pre->suc->cur->rear

     */
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head), pre = dummy;
        while (pre.next != null && pre.next.next != null) {
            ListNode cur = pre.next, suc = cur.next, rear = suc.next;
            pre.next = suc;
            suc.next = cur;
            cur.next = rear;
            pre = cur;
        }
        return dummy.next;
    }
}