solution.md 2.4 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
# 排序链表

<p>给你链表的头结点 <code>head</code> ,请将其按 <strong>升序</strong> 排列并返回 <strong>排序后的链表</strong></p>

<p><b>进阶:</b></p>

<ul>
	<li>你可以在 <code>O(n log n)</code> 时间复杂度和常数级空间复杂度下,对链表进行排序吗?</li>
</ul>

<p> </p>

<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" style="width: 302px; "/>
<pre>
<b>输入:</b>head = [4,2,1,3]
<b>输出:</b>[1,2,3,4]
</pre>

<p><strong>示例 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" style="width: 402px; " />
<pre>
<b>输入:</b>head = [-1,5,3,4,0]
<b>输出:</b>[-1,0,3,4,5]
</pre>

<p><strong>示例 3:</strong></p>

<pre>
<b>输入:</b>head = []
<b>输出:</b>[]
</pre>

<p> </p>

<p><b>提示:</b></p>

<ul>
	<li>链表中节点的数目在范围 <code>[0, 5 * 10<sup>4</sup>]</code> 内</li>
	<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
</ul>


## template

```python
ToTensor's avatar
ToTensor 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        if head == None:
            return None
        else:
            return self.mergeSort(head)

    def mergeSort(self, head):
        if head.next == None:
            return head
        fast = head
        slow = head
        pre = None

        while fast != None and fast.next != None:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None

        left = self.mergeSort(head)
        right = self.mergeSort(slow)

        return self.merge(left, right)

    def merge(self, left, right):
        tempHead = ListNode(0)
        cur = tempHead
        while left != None and right != None:
            if left.val <= right.val:
                cur.next = left
                cur = cur.next
                left = left.next
            else:
                cur.next = right
                cur = cur.next
                right = right.next
        if left != None:
            cur.next = left
        if right != None:
            cur.next = right
        return tempHead.next
ToTensor's avatar
ToTensor 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

```

## 答案

```python

```

## 选项

### A

```python

```

### B

```python

```

### C

```python

```