24. Swap Nodes in Pairs

1.問題

  • 給予一個linked list, 兩兩互換

2.想法

  • 提問

  • function header, parameter

  • test inpu

  • 說明想法

    • 遞迴作法:

      • base case: 不到兩個node的話, return head

      • 將next = curr->next

      • curr-> next 接到 curr->next與curr->next->next排序的結果

      • 將next->next = curr, return next

  • 測試計算複雜度: O(n)

3.程式碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }
        
        ListNode* next = head->next;
        head->next = swapPairs(head->next->next);
        next->next = head;
        
        return next;
    }
};

Last updated