用插入排序對鍊錶排序
given1->3->2->0->null
, return0->1->2->3->null
實現**:
"""definition of listnode
class listnode(object):
def __init__(self, val, next=none):
self.val = val
self.next = next
"""class solution:
"""@param head: the first node of linked list.
@return: the head of linked list.
"""def insertionsortlist(self, head):
# write your code here
if not head:
return head
dummy = listnode(0)
dummy.next, curt = head, head
while curt.next:
#如果當前結點小於下乙個結點,就遞推
if curt.val < curt.next.val:
curt = curt.next
#當前結點大於下乙個結點
else:
#prev 排序結點
prev = dummy
#找到curt在prev中的位置
while prev.next.val < curt.next.val:
prev = prev.next
#從未排序鍊錶中刪除該結點
temp = curt.next
curt.next = temp.next
#將該結點加入排序鍊錶
temp.next = prev.next
prev.next = temp
return dummy.next
lintcode練習 98 鍊錶排序
在 o n log n 時間複雜度和常數級的空間複雜度下給鍊錶排序。給出1 3 2 null,給它排序變成1 2 3 null.分別用歸併排序和快速排序做一遍。實現 definition of listnode class listnode object def init self,val,next...
lintcode練習 102 帶環鍊錶
給定乙個鍊錶,判斷它是否有環。給出 21 10 4 5,tail connects to node index 1,返回 true 不要使用額外的空間 實現 思路 快慢指標的典型應用,使用快指標 fast 與慢指標 slow,slow每次後移一位,fast 每次後移兩位,當fast 與 slow 指...
173鍊錶插入排序
樣例 given 1 3 2 0 null,return 0 1 2 3 null 注意單鏈表插入排序和陣列插入排序的不同 陣列插入排序是從排好序的部分的最後乙個節點往前找,找到第乙個比它小的數,然後插到其後面 而單鏈表只能從前往後遍歷,找到第乙個比當前節點大的值結束,因此在遍歷已經排好序的鍊錶部分...