# 第一种 将节点的值放入数组中 快排调整 再重新链接
class Node(object):
def __init__(self,val=None):
self.val = val
self.next = None
def smallequalbigger(head,num):
if head == None or head.next == None:
return head
#计节点数目
cur = head
n = 0
while cur!=None:
n+=1
cur = cur.next
#将节点添加到列表中
list = []
cur = head
while cur != None:
list.append(cur)
cur = cur.next
#调整位置
partition(list,num)
#调整之后再重新连接
for i in range(n-1):
list[i].next = list[i+1]
list[-1].next = None
return list[0]
def partition(list,num):
less = -1
more = len(list)
cur = 0
while cur<more:
if list[cur].val < num:
list[cur],list[less+1] = list[less+1],list[cur]
less+=1
cur+=1
elif list[cur].val == num:
cur+=1
else:
list[cur],list[more-1] = list[more-1],list[cur]
more-=1
这种方法做不到稳定性,并且需要额外准备数组空间
进阶要求,保证稳定性,并且只用有限几个变量
遍历一遍 找到第一个小于num的数 第一个等于num的数 第一个大于num的数 再遍历 将第二个小于num的数,挂在
第一个小于num的数的下边
class Node(object):
def __init__(self,val=None):
self.val = val
self.next = None
def smallequalbigger(head,num):
if head == None or head.next == None:
return head
#相当于划分了三个箱子 小于的 等于的 大于的 头和尾
smallHead = None
smallTail = None
equalHead = None
equalTail = None
bigHead = None
bigTail = None
#分配悬挂
while head!=None:
next = head.next
head.next = None
if head.val < num:
if smallHead==None:
#说明这是第一个
smallHead = head
smallTail = head
else:
smallTail.next = head
smallTail = head
elif head.val == num:
if equalHead==None:
equalHead = head
equalTail = head
else:
equalTail.next = head
equalTail = head
else:
if bigHead==None:
bigHead = head
bigTail = head
else:
bigTail.next = head
bigTail = head
head = next
head = None
#判断各个区域是否有数
if smallTail!=None:
head = smallHead
if equalHead!=None:
smallTail.next = equalHead
elif bigHead!=None:
smallTail.next = bigHead
if equalTail==None:
head = head if head!=None else equalHead
if bigHead!=None:
equalTail.next = bigHead
return head if head != None else bigHead