Problem: 148. 排序链表
思路 & 解题方法
不想用归并排序,干脆用数组做了。
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( n l o g n ) O(nlogn) O(nlogn)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
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