1.归并排序
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self.mergeSort(head)
def mergeSort(self, head):
#处理特殊情况
if head is None:
return head
if head.next is None:
return head
pNode = head.next
if pNode.next is None:
if head.val > pNode.val:
temp = pNode.val
pNode.val = head.val
head.val = temp
return head
#寻找链表的中间节点
pSlow = head
pFast = head.next
while pSlow and pFast:
pSlow = pSlow.next
pFast = pFast.next
if pFast and pFast.next:
pFast = pFast.next
else:
break
#归并排序
rightList = self.mergeSort(pSlow.next)
pSlow.next = None
leftList = self.mergeSort(head)
# merge
pHead = None
pEnd = None
if leftList.val <= rightList.val:
pHead = leftList
pEnd = pHead
leftList = leftList.next
else:
pHead = rightList
pEnd = pHead
rightList = rightList.next
while leftList and rightList:
if leftList.val <= rightList.val:
pEnd.next = leftList
pEnd = pEnd.next
leftList = leftList.next
else:
pEnd.next = rightList
pEnd = pEnd.next
rightList = rightList.next
while leftList:
pEnd.next = leftList
pEnd = pEnd.next
leftList = leftList.next
while rightList:
pEnd.next = rightList
pEnd = pEnd.next
rightList = rightList.next
pEnd.next = None
return pHead
2.快速排序(超时)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tail = head
if head is None:
return head
while tail.next:
tail = tail.next
return self.QuickSort(head, tail)[0]
def QuickSort(self, head, tail):
# 处理特殊情况
if head is None:
return head, head
if head.next is None:
return head, head
pNode = head.next
if pNode.next is None:
if head.val > pNode.val:
temp = pNode.val
pNode.val = head.val
head.val = temp
return head, head.next
key = head.val
p = head.next
leftHead = None
leftFront = None
leftTail = None
rightHead = None
rightFront = None
rightTail = None
while p:
if p.val < key:
if leftHead is None:
leftHead = p
leftFront = leftHead
else:
leftFront.next = p
leftFront = leftFront.next
else:
if rightHead is None:
rightHead = p
rightFront = rightHead
else:
rightFront.next = p
rightFront = rightFront.next
p = p.next
if leftFront:
leftFront.next = None
if rightFront:
rightFront.next = None
leftTail = leftFront
rightTail = rightFront
if leftHead:
leftHead, leftTail = self.QuickSort(leftHead, leftTail)
if rightHead:
rightHead, rightTail = self.QuickSort(rightHead, rightTail)
subHead = None
subEnd = None
if leftHead and rightHead:
leftTail.next = head
head.next = rightHead
head = leftHead
subHead = head
subEnd = rightTail
elif leftHead:
leftTail.next = head
head.next = None
subEnd = head
head = leftHead
subHead = head
elif rightHead:
head.next = rightHead
subHead = head
subEnd = rightTail
return subHead, subEnd