148排序链表

class ListNode:
def __init__(self, x):
self.val = x
self.next = None
a = ListNode(1)
b = ListNode(3)
c = ListNode(2)
d = ListNode(1)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
# 这道题是用归并排序的方法
class Solution:
def sortList(self, head: ListNode) -> ListNode:
# 首先判断链表是否只有一个节点,或者链表为空
if not head or not head.next:return head
# 定义两个快慢指针,用来找出链表的中间节点,用于等下递归的出口和入口
slow,fast = head,head.next
# 遍历链表,找出中间那个节点
while fast and fast.next:
slow,fast = slow.next,fast.next.next
# 然后将链表分为两边,进行递归归并排序
slow.next,mid = None,slow.next
left = self.sortList(head)
right = self.sortList(mid)
# 定义一个节点,用来当做重新排序后链表的头结点
node = ListNode(0)
node1 = node
# 遍历然后用于归并排序后的合成
while left and right:
if left.val > right.val:
node.next,right = right,right.next
else:
node.next,left = left,left.next
node = node.next
node.next = left if left else right
# 最后返回这个链表。
return node1.next


A = Solution()
print(A.sortList(a))



posted @ 2020-07-31 12:49  月为暮  阅读(35)  评论(0编辑  收藏