单链表左边中间相等右边大的形式python实现

# 第一种  将节点的值放入数组中 快排调整  再重新链接
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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值