> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/24.-swap-nodes-in-pairs.md).

# 24. Swap Nodes in Pairs

## 1.問題

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

![](/files/-LM7LEblavQzIJZQvC4D)

## 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;
    }
};
```
