给定一个节点数为n的无序单链表,对其按升序排序。
数据范围:,保证节点权值在之内。
要求:空间复杂度 ,时间复杂度
class Solution: def sortInList(self, head: ListNode) -> ListNode: if not head&nbs***bsp;not head.next: return head # 如果是基本情况(单个节点或空列表),则返回当前节点 # 寻找中点 slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None left = self.sortInList(head) right = self.sortInList(mid) # 合并排序后的列表 dummy = ListNode(0) cur = dummy while left and right: if left.val < right.val: cur.next = left left = left.next else: cur.next = right right = right.next cur = cur.next cur.next = left&nbs***bsp;right return dummy.next
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 the head node # @return ListNode类 # class Solution: def sortInList(self , head: ListNode) -> ListNode: # write code here if head is None: return None s = [] while head : s.append(head.val) head = head.next s = sorted(s) res = ListNode(0) temp = res for i in s : temp.next = ListNode(i) temp = temp.next return res.next
class Solution: def sortInList(self , head: ListNode): # write code here def quickSort(head) -> ListNode: if head == None&nbs***bsp;head.next == None: return head index = head.val lNode = None rNode = None mNode = None p = head # 插在头节点处 while p != None: temp = ListNode(p.val) if p.val == index: temp.next = mNode mNode = temp elif p.val > index: temp.next = rNode rNode = temp else: temp.next = lNode lNode = temp p = p.next # 返回了头节点,且有可能为None l1 = quickSort(lNode) l2 = getTail(mNode) l2.next = quickSort(rNode) if l1 == None: return mNode else: l1Tail = getTail(l1) l1Tail.next = mNode return l1 def getTail(head): if head == None: return None while head.next != None: head = head.next return head return quickSort(head)
# @param head ListNode类 the head node # @return ListNode类 # class Solution: def sortInList(self , head ): # write code here list1 = [] while(head): list1.append(head.val) head = head.next list1.sort() temp = ListNode(0) pHead = temp for i in list1: pHead.next = ListNode(i) pHead = pHead.next return temp.next