心路历程:
这道题通过很简单,但是如果想要用O(1)的空间复杂度+O(nlogn)的时间复杂度的话,可能得需要双指针+快排的思路。
解法:遍历模拟
# 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]:
res = []
t1 = head
while t1:
res.append(t1.val)
t1 = t1.next
res.sort()
t2 = head
c = 0
while t2:
t2.val = res[c]
c+=1
t2 = t2.next
return head