class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def getmid(head):
slow = fast = head
if head is None:
return slow
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def merge(l, r):
a = ListNode(0)
q = a
while l and r:
if l.val > r.val:
q.next = r
r = r.next
else:
q.next = l
l = l.next
q = q.next
if l:
q.next = l
if r:
q.next = r
return a.next
def sortList(head):
if head is None or head.next is None:
return head
mid = getmid(head)
l = head
r = mid.next
mid.next = None
return merge(sortList(l), sortList(r))
head = ListNode(5)
b = ListNode(4)
c = ListNode(2)
d = ListNode(3)
e = ListNode(6)
head.next = b
b.next = c
c.next = d
d.next = e
head = sortList(head)
while head is not None:
print(head.val, end=' ')
head = head.next
排序链表
最新推荐文章于 2024-06-22 21:53:36 发布