Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 24. Swap Nodes in Pairs

Rain Hu

24. Swap Nodes in Pairs


一、題目

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

Example 1:
swap_ex1

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Recursion

ListNode* swapPairs(ListNode* head) {
    if (!head || !head->next) return head;  // 先確定終止條件
    ListNode* next = head->next;            // 兩個節點為單位,所以在每一個遞迴內控制兩個節點
    head->next = swapPairs(next->next);     // 每個單位的尾巴接回傳值的頭部
    next->next = head;                      // 實做每個單位裡面的反轉
    return next;                            // 因為單位的尾巴要接到下一個單位的頭部,故這裡要回傳單位的頭位
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 25. Reverse Nodes in k-Group
Next
[LeetCode] 931. Minimum Falling Path Sum