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

时间:2013-05-25 18:37:45

标签: python sorting linked-list sublist

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这样的输入,在开头未分类! 任何人都可以帮我解决..

1 个答案:

答案 0 :(得分:1)

我无法找出你的代码,但我怀疑无限循环的原因是你将temp设置为current而不是current.value,所以你是翻转利弊细胞本身而不是内容。这可能会创建循环链接列表,您可以无限迭代。

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

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