Skip to main content
 首页 » 编程设计

python之在链表 Python 中对子列表进行排序

2025年05月04日9exmyth

def sublist(head): 
    current=head 
    #temp=current #If my list is 3->2->1->4->5->6 it goes into an infinite loop 
    while ((current.next is not None) and current.value < current.next.value ): 
        temp=current 
        current=current.next 
    start=current 
    while ((current.next is not None) and current.value > current.next.value ): 
        current=current.next 
    last=current.next 
    current.next=None 
    first=reverse_linked_list(start) 
    temp.next=first 
 
    while first.next is not None: 
        first=first.next 
    first.next=last 
 
    while head: 
        print head.value 
        head=head.next 
    return head 

代码的工作: 我将代码输入作为无序子列表,其中列表中的子列表按降序排列,链表的其余部分按升序排列。

代码适用于像这样的输入 1, 2, 3, 4 ,5, 9, 8, 7, 10 和 1,10,9,8,7,6,5.. 即中间和末尾的未排序列表,但如果列表不起作用对于像 3、2、1、4、5、6 这样的输入,在开始时是未排序的! 任何人都可以帮助我吗..

请您参考如下方法:

我无法理解你的代码,但我怀疑无限循环的原因是你将 temp 设置为 current 而不是 current .value,所以你要翻转 cons 单元格本身而不是它们的内容。这可能会创建您要无限迭代的循环链表。

但是,我会这样做(使用基本的冒泡排序算法):

from functools import total_ordering 
 
@total_ordering 
class cons: 
    def __init__(self, head, tail=None): 
        self.head = head 
        self.tail = tail 
 
    @classmethod 
    def fromlist(self, l): 
        if l == []: 
            return None 
        return cons(l[0], cons.fromlist(l[1:])) 
 
    def tolist(self): 
        if self.tail == None: 
            return [self.head] 
        else: 
            return [self.head] + self.tail.tolist() 
 
    def flip(self): 
        if not self.tail == None: 
            tmp = self.head 
            self.head = self.tail.head 
            self.tail.head = tmp 
 
    def __lt__(self, other): 
        if other == None: 
            return True 
        else:  
            return self.head < other.head 
    def __eq__(self, other): 
        if other == None: 
            return False 
        else: 
            return self.head == other.head 
 
def llsort(head): 
    changed = True 
    while changed: 
        changed = False 
        current = head 
        while current != None: 
            if current > current.tail: 
                current.flip() 
                changed = True 
            current = current.tail 

编辑:__lt__ 和flip 对其他用途不稳健。事实上,我只把 __lt__ 和 __eq__ 放在那里,因为我试图找出一种方法来只使用 python 的一个内置排序系统,但无法得到它上类。稍微简化一下:

class cons: 
    def __init__(self, head, tail=None): 
        self.head = head 
        self.tail = tail 
 
    def flip(self): 
        if not self.tail == None: 
            tmp = self.head 
            self.head = self.tail.head 
            self.tail.head = tmp 
 
 
def llsort(head): 
    changed = True 
    while changed: 
        changed = False 
        current = head 
        while current.tail != None: 
            if current.head > current.tail.head: 
                current.flip() 
                changed = True 
            current = current.tail