Merge sort of linked list
Code that timed out
Class Solution:def merge (self, head1, head2): if head1 = = None:return head2if head2 = None:return head1# head1 and Head2 p oint to the same link listif head1 = = Head2:return Head1head = Nonetail = none# The small pointer point to smaller of. While Head1 and head2:if head1.val <= head2.val:small = head1head1 = Head1.nextelse:small = head2head2 = head2.next# th E First Nodeif Tail = = None:tail = Smallhead = Smallelse:tail.next = Smalltail = small# link the remaind nodesif head1 = = None:head1 = Head2tail.next = Head1return headdef sortlist (self, head): if head = = None or Head.next = = None:return head# W E use a fast pointer which go steps each time and # a slow pointer which go one step each time to get the # middle of The link Listslow = Headfast = Headwhile Fast.next and fast.next.next:fast = Fast.next.nextslow = slow.next# Slow point to The middle nowhead2 = slow.next# We cut of the linked list at middleslow.next = Noneleft = Self.sortlist (head) right = Sel F.sortlist (HEAD2) returnSelf.merge (left, right)
Mainly in the time of the merge. To infer a first node
AC Code
Class Solution:def merge (self, head1, head2): if head1 = = None:return head2if head2 = None:return head1# head1 and Head2 p oint to the same link listif head1 = = Head2:return Head1head = ListNode ( -1) tail = head# The small pointer point to smaller of Two.while Head1 and head2:if head1.val <= head2.val:small = head1head1 = Head1.nextelse:small = Head2head2 = head2. Nexttail.next = Smalltail = small# link the remaind nodesif head1 = = None:head1 = Head2tail.next = Head1return head.nextde F Sortlist (Self, head): if head = = None or Head.next = = None:return head# We use a fast pointer which go both steps each Tim E and # A slow pointer which go one step each time to get the # middle of the link Listslow = Headfast = Headwhile fast.ne XT and fast.next.next:fast = Fast.next.nextslow = slow.next# Slow point to the middle nowhead2 = slow.next# we cut of the Linked list at middleslow.next = Noneleft = Self.sortlist (head) right = Self.sortlist (head2) return Self.merge (left, right)
When the merge is built, a pseudo-head node is created, and when processed, it is not inferred whether it is the first node, although AC, but the time is above 5500ms. The C + + code only needs more than 200 MS, the gap is still larger
"Leetcode" sort list (python)