您的位置:首页 > 其它

链表排序-归并排序和快速排序

2017-11-25 16:40 323 查看

LeetCode148 SortList

题意:给定一个链表,要求用O(n log n) 的复杂度进行排序。

直观的链表归并排序:

class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if  not head or not head.next :return head
p , one,two=ListNode(0),head,head
p.next=head
while two and two.next:
p = one
one , two = one.next,two.next.next
p.next=None  # 截断
lhead=self.sortList(head)
rhead=self.sortList(one)
return self.merge(lhead,rhead)

def merge(self,lhead,rhead):
head = ListNode(-1) #表头
p,prep=None,head
while lhead and rhead:
if lhead.val < rhead.val:
p ,lhead= lhead,lhead.next
else:
p,rhead=rhead,rhead.next
prep.next=p
prep=prep.next

while lhead:
p , lhead= lhead,lhead.next
prep.next=p
prep=prep.next
while rhead:
p,rhead=rhead,rhead.next
prep.next=p
prep=prep.next

return head.next

 

快速排序,因为是链表不能用下标快速访问,挖坑法不适用,这里采用《算法导论》中的单向双指针法,end记录边界不采用None截断

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
def sortList(self, head):
"""
sort list using quick sort
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
tail = self.get_tail(head)
head, tail = self.quick_sort(head, tail)
tail.next = None
return head

def quick_sort(self, head, tail):
"""
Sort in place
:param head:
:param tail:
:return:
"""
if head is not tail:
head_left, tail_left, head_ref, tail_ref, head_right, tail_right = self.quicksort_partition(head, tail)
if head_left is None:  # if there is no node in left part after partition
head = head_ref
else:
head_left, tail_left = self.quick_sort(head_left, tail_left)
head = head_left
tail_left.next = head_ref
if head_right is None:  # if there is no node in right part after partition
tail = tail_ref
else:
head_right, tail_right = self.quick_sort(head_right, tail_right)
tail_ref.next = head_right
tail = tail_right
return head, tail

def quicksort_partition(self, head, tail):
reference = tail
head_ref, tail_ref = reference, reference
head_left, tail_left, head_right, tail_right = None, None, None, None

sentinel = ListNode(None)  # use sentinel to simplify the code
sentinel.next = head
node = sentinel
while node.next is not tail:
node = node.next
if node.val > reference.val:  # put node into right part
if head_right is not None:
tail_right.next = node
tail_right = node
else:  # right part is empty
head_right = node
tail_right = node
elif node.val < reference.val:  # put node into left part
if head_left is not None:
tail_left.next = node
tail_left= node
else:  # left part is empty
head_left = node
tail_left = node
else:  # put node into reference part
tail_ref.next = node
tail_ref = node
return head_left, tail_left, head_ref, tail_ref, head_right, tail_right

def get_tail(self, node):
while node.next:
node = node.next
return node

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: