此題目對應於LeetCode 148
題目要求:
Sort a linked list in O(n log n)
time using constant space complexity.
用O(n log n) 的排序算法,很容易讓人想到用遞推去做。
思路就是將單鏈表一分爲二劃分成兩個子問題,然後遞歸調用算法,最後在做一個對兩個
有序的單鏈表的合併操作(O(n))。
按照主定理:
T(n) = 2T(n/2) + n
則 T(n) = n = f(n), 則 T(n) = O(nlogn)
單鏈表一分爲二就直接從單鏈表中間劃分
下面附上python代碼:
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
def mergeTwoLists(self, l1, l2):#合併兩個有序的鏈表
if not l1:
return l2
if not l2:
return l1
prenode = ListNode(1)
p = prenode
while l1 and l2:
if l1.val <= l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
if l2:
p.next = l2
return prenode.next
def sortList(self, head):
if not head or not head.next:
return head
prenode = head
p1 = prenode
p2 = prenode
l = 0
while p1:
l += 1
p1 = p1.next
mid = l/2
k = 0
l1 = prenode
while p2: # 將單鏈表從中間一分爲二
if k >= mid-1:
tmp = p2.next
p2.next = None
l2 = tmp
break
else:
p2 = p2.next
k += 1
t1 = self.sortList(l1)
t2 = self.sortList(l2)
return self.mergeTwoLists(t1,t2)