https://leetcode.com/problems/sort-list/
这里又复习了一遍merge list的操作。用归并排序就行
class Solution(object):
def mergeList(self, head1, head2):
if not head1: return head2
if not head2: return head1
dummy = ListNode(0)
p = dummy
while head1 and head2:
if head1.val < head2.val:
p.next = head1
head1 = head1.next
p = p.next
else:
p.next = head2
head2 = head2.next
p = p.next
if not head1:
p.next = head2
if not head2:
p.next = head1
return dummy.next
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
slow, fast = head, head
while fast.next and fast.next.next:
#这里要注意fast只需要到倒数第二个node就行,反正就只是将linkedlist分割而已。不需要准确二分之一
#如果这里是while fast,那么可能fast就是None,然后slow是最后一个node,这样就导致linkedlist没有分成两半,出现死循环
slow = slow.next
fast = fast.next.next
head1, head2 = head, slow.next
slow.next = None
head1, head2 = self.sortList(head1), self.sortList(head2)
return self.mergeList(head1, head2)