Sort a linked list using insertion sort.
思路:思路上和insertion sort一致,需要注意的是,需要判斷前一個元素是否比當前元素大,如果大的話,則需要insertion, 從head開始遍歷直至找到插入的位置,注意邊界條件
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if head == None or head.next == None:
return head
newhead = head
pre = newhead
node = newhead.next
while node != None:
if node.val < pre.val:
pre.next = node.next
if node.val < newhead.val:
node.next = newhead
newhead = node
else:
phead = newhead
while phead.next.val < node.val:
phead = phead.next
continue
node.next = phead.next
phead.next = node
node = pre.next
else:
node = node.next
pre = pre.next
return newhead