> 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/147.-dui-lian-biao-jin-hang-cha-ru-pai-xu.md).

# 147. 对链表进行插入排序

<https://leetcode-cn.com/problems/insertion-sort-list/>

## 解法一：暴力

分两段，有序段和无序（待处理）段。

```python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def insertionSortList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        work = head.next  #工作指针，无序段第一个结点。紧接在在有序段后面
        #有序段初始，只有[head]
        head.next = None
        Head = ListNode(0)  #辅助头结点
        Head.next = head
        while work:  #每次处理一个，处理完后移，直到末尾
            pre = Head
            p = Head.next
            #在有序段中找合适位置插入
            while p and work.val > p.val:
                pre = p
                p = p.next

            tmp = work
            work = work.next
            pre.next = tmp
            tmp.next = p
            
        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/147.-dui-lian-biao-jin-hang-cha-ru-pai-xu.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.
