很基础,我是用三种=实现都TLE了.还请大家指教。。。
第一种,递归的:
def insertionSortList1(self,head):
if head == None:
return head
left = head.next
head.next = None
left = self.insertionSortList(left)
if left==None:
return head
if head.val <= left.val:
head.next = left
return head
else:
ret = left
while left.next !=None:
if head.val <= left.next.val:
head.next=left.next
left.next = head
return left
left = left.next
left.next = head
return ret
第二种,维护一个已经排好序的列表,从未排序列表中取出一个找到对的位置,插入操作不涉及拆链和接链。而是置换节点的值。
def insertionSortList2(self,head):
if head == None or head.next == None:
return head
else:
cur = head.next
while cur != None:
tmp_h = head
while tmp_h.val < cur.val and tmp_h != cur:
tmp_h = tmp_h.next
pre_val = cur.val
#print '\nhaha',pre_val
while tmp_h != cur:
tmp_val = tmp_h.val
tmp_h.val = pre_val
pre_val = tmp_val
tmp_h = tmp_h.next
tmp_h.val=pre_val
cur = cur.next
return head
第三种:和第二种方法一样,不同的是找到要插入位置之后,使用链表插入的方式。
def insertionSortList3(self,head):
if head == None or head.next == None:
return head
next_ = head.next.next
pivot = head.next
head.next = None
pivot.next = None
while True:
if pivot.val <=head.val:
pivot.next = head
head = pivot
else:
tmp_h = head
while tmp_h.next != None:
if pivot.val <= tmp_h.next.val:
pivot.next = tmp_h.next
tmp_h.next = pivot
break
tmp_h= tmp_h.next
if tmp_h.next == None:
tmp_h.next=pivot
pivot = next_
if next_ == None:
break
next_=next_.next
pivot.next = None
return head