classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next defcreateLink_rearinsert(lista): head = ListNode(-1) rear = head for i in lista: new_node=ListNode(i) rear.next=new_node rear=new_node return head.next
classSolution: defsortList(self, head: ListNode) -> ListNode: ifnot head: return head dic=dict() while head: dic[head]=head.val head=head.next #print(dic) new_dic=sorted(dic.items(),key=lambda item:item[1]) head= ListNode(-1) rear = head for d in new_dic: rear.next = d[0] rear = rear.next rear.next=None return head.next
if __name__=="__main__": head = [-1,5,3,4,0] new_a=createLink_rearinsert(head) a1 = Solution() p=a1.sortList(new_a) list_head=[] while p!=None: list_head.append(p.val) p=p.next print(list_head)
classSolution: defsortList(self, head: ListNode) -> ListNode: ifnot head ornot head.next: return head # termination. # cut the LinkedList at the mid index. slow, fast = head, head.next while fast and fast.next: fast, slow = fast.next.next, slow.next mid, slow.next = slow.next, None# save and cut. # recursive for cutting. left, right = self.sortList(head), self.sortList(mid) # merge `left` and `right` linked list and return it. h = res = ListNode(0) while left and right: if left.val < right.val: h.next, left = left, left.next else: h.next, right = right, right.next h = h.next h.next = left if left else right return res.next if __name__=="__main__": head = [-1,5,3,4,0,6,2] new_a=createLink_rearinsert(head) a1 = Solution() p=a1.sortList(new_a) list_head=[] while p!=None: list_head.append(p.val) p=p.next print(list_head)
classSolution: defsortList(self, head: ListNode) -> ListNode: h, length, intv = head, 0, 1 # 统计链表长度 while h: h, length = h.next, length + 1 res = ListNode(0) res.next = head # merge the list in different intv. while intv < length: pre, h = res, res.next while h: # get the two merge head `h1`, `h2` h1, i = h, intv while i and h: h, i = h.next, i - 1 if i: break# no need to merge because the `h2` is None. h2, i = h, intv while i and h: h, i = h.next, i - 1 c1, c2 = intv, intv - i # the `c2`: length of `h2` can be small than the `intv`. # merge the `h1` and `h2`. while c1 and c2: if h1.val < h2.val: pre.next, h1, c1 = h1, h1.next, c1 - 1 else: pre.next, h2, c2 = h2, h2.next, c2 - 1 pre = pre.next pre.next = h1 if c1 else h2 while c1 > 0or c2 > 0: pre, c1, c2 = pre.next, c1 - 1, c2 - 1 pre.next = h intv *= 2 return res.next
if __name__=="__main__": head = [-1,5,3,4,0,6,7,2] new_a=createLink_rearinsert(head) a1 = Solution() p=a1.sortList(new_a) list_head=[] while p!=None: list_head.append(p.val) p=p.next print(list_head)