单链表的排序
拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortInList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
# 快慢指针找中点
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 截断链表
mid = slow.next
slow.next = None
# 递归排序左右子链表
left = self.sortInList(head)
right = self.sortInList(mid)
# 合并两个链表
dummy = ListNode(0)
cur = dummy
while left and right:
if left.val < right.val:
cur.next = left
left = left.next
else:
cur.next = right
right = right.next
cur = cur.next
cur.next = left or right
return dummy.next
if __name__ == '__main__':
head = ListNode(4)
head.next = ListNode(2)
head.next.next = ListNode(1)
head.next.next.next = ListNode(3)
solution = Solution()
sorted_head = solution.sortInList(head)
curr = sorted_head
while curr:
print(curr.val, end=" ")
curr = curr.next
归并排序的链表版本