【Leetcode/解题报告】 148. Sort List

题目来源:

https://leetcode.com/problems/sort-list/description/

题意分析:

    用O(nlogn)的时间复杂度将一个链表排序。

题目思路:

    用归并排序。若链表节点数小于等于1,直接返回,否则,先将链表从中间切断,对这两个链表排序,再用O(n)的时间复杂度将这两个有序链表组合成一个。组合方法为创建一个空的头指针,比较两个链表的头节点,将较小的一个加入头节点并从原来的链表中删除。直到一个链表为空,将另一个链表加入尾部。

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
	def sortList(self, head):
		"""
		:type head: ListNode
		:rtype: ListNode
		"""
		if head == None: return None
		if head.next == None: return head
		else:
			mid = self.cut(head)
			head = self.sortList(head)
			mid = self.sortList(mid)
			return self.merge(head, mid)

	def cut(self, head):
		'''
		type head: ListNode
		rtype: ListNode
		'''
		if head == None: return None
		p, mid = head.next, head
		while p != None:
			p = p.next
			if p != None:
				p = p.next
				mid = mid.next
		half = mid.next
		mid.next = None
		return half

	def merge(self, first, second):
		'''
		type first: ListNode
		type second: ListNode
		rtype: ListNode
		'''
		if first == None: return second
		if second == None: return first
		p1, p2, head = first, second, ListNode(0)
		p = head
		while p1 != None and p2 != None:
			if p1.val < p2.val:
				p.next = p1
				p = p.next
				p1 = p1.next
			else:
				p.next = p2
				p = p.next
				p2 = p2.next
		if p1 != None: p.next = p1
		else: p.next = p2
		return head.next

猜你喜欢

转载自blog.csdn.net/weixin_38196217/article/details/80172957