> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1-200/24.-liang-liang-jiao-huan-lian-biao-zhong-de-jie-dian.md).

# 24. 两两交换链表中的节点

<https://leetcode-cn.com/problems/swap-nodes-in-pairs/>

## 解法一：

一次遍历，用i，j指针表示前后结点对，pre记录i前驱，将i和j交换。

```python
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        Head = ListNode(0)
        Head.next = head
        if not head or not head.next:
            return head
        pre, i ,j = Head, head, head.next
        while i and j:
            #交换
            i.next = j.next
            j.next = i
            pre.next = j
            #更新
            pre = i
            i = i.next
            if i:    #若i非空才有j
                j = i.next
        return Head.next
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://cai-sen-se.gitbook.io/leetcode/1-200/24.-liang-liang-jiao-huan-lian-biao-zhong-de-jie-dian.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.
