Problem: 148. 排序链表


文章目录

  • 思路 & 解题方法
  • 复杂度
  • Code


思路 & 解题方法

不想用归并排序,干脆用数组做了。

复杂度

时间复杂度:

添加时间复杂度, 示例: 排序链表【链表】_数据结构

空间复杂度:

添加空间复杂度, 示例: 排序链表【链表】_数据结构_02

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        l = []
        cur = head
        while cur:
            l.append(cur.val)
            cur = cur.next
        l.sort()
        ans = now = ListNode(0, None)
        for x in l:
            t = ListNode(x, None)
            now.next = t
            now = t
        return ans.next