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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/24.-swap-nodes-in-pairs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
