链表问题-----排序
Posted lee-yl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表问题-----排序相关的知识,希望对你有一定的参考价值。
一、题目:将单向链表按某值划分为左边小、中间相等、右边大的形式
简单的思路:时间O(N),空间O(N)
采用一个数组来存储链表中的值,然后对该数组进行快排,然后再连成链表,快排思想如下图所示:
代码:
class Node: def __init__(self,value): self.value = value self.next = None #快排思想 def partition(arr,pivot): small = -1 big = len(arr) index = 0 while index != big: if arr[index] < pivot: small += 1 arr[small] , arr[index] = arr[index] , arr[small] index += 1 elif arr[index] == pivot: index += 1 else: big -= 1 arr[index] , arr[big] = arr[big] , arr[index] return arr #链表操作 def listSort(head,pivot): if not head: return head #将链表存储在数组中 arr = [] while head: arr.append(head.value) head = head.next arr = partition(arr,pivot) #创建链表 node = Node(arr[0]) p = node for i in range(1,len(arr)): p.next = Node(arr[i]) p = p.next return node head = Node(9) head.next = Node(0) head.next.next = Node(4) head.next.next.next = Node(3) head.next.next.next.next = Node(1) pivot = 3 node = listSort(head,pivot)
进阶思想:时间O(N),空间O(1)
代码:
class Node: def __init__(self,value): self.value = value self.next = None def listPartition(head,pivot): if not head: return head sH = None sT = None eH = None eT = None bH = None bT = None while head: next = head.next head.next = None if head.value < pivot: if not sH: sH = head sT = head else: sT.next = head sT = head elif head.value == pivot: if not eH: eH = head eT = head else: eT.next = head eT = head else: if bH == None: bH = head bT = head else: bT.next = head bT = head head = next if sT: sT.next = eH eT = eT if eT else sT if eT: eT.next = bH return sH if sH else eH if eH else bH arr = [9,1,4,5,6,3,8] head = Node(arr[0]) p = head for i in range(1,len(arr)): p.next = Node(arr[i]) p = p.next pivot = 5 res = listPartition(head,pivot)
以上是关于链表问题-----排序的主要内容,如果未能解决你的问题,请参考以下文章