2013-05-25 44 views
2
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 

代碼的工作: 我給輸入代碼爲無序子列表,其中列表中的子列表是decending秩序和鏈接列表的其餘部分按升序爲了..排序的子列表的鏈接列表的Python

代碼工作,用於輸入像 1,2,3,4,5,9%,8,7,10和1,10,9,8,7,6,5 ..即一個未排序列表在中間和結束,但它不起作用,如果列表未分類在開始輸入像3,2,1,4,5,6! 誰能幫我請..

+0

我認爲這將有所幫助,如果你添加一些評論和/或描述如何排序應該工作。這是你自己的自定義排序算法還是你想實現其中一個知名的? –

+1

相關:[用於Python中單連接線性列表的Mergesort算法](https://gist.github.com/zed/5651186) – jfs

回答

1

我無法弄清楚你的代碼,但我懷疑無限循環的原因是你設置tempcurrent而不是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 
+0

我不應該使用任何內置函數..也不能使用中間列表..無論如何感謝您的幫助..我瞭解我的錯誤分析您的代碼! :) – user2205015