Sort a linked list using insertion sort. A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ classSolution: """ @param head: The first node of linked list. @return: The head of linked list. """ definsertionSortList(self, head): dummy = ListNode(0) cur = head while cur isnotNone: pre = dummy while pre.nextisnotNoneand pre.next.val < cur.val: pre = pre.next temp = cur.next cur.next = pre.next pre.next = cur cur = temp return dummy.next
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ classSolution: """ @param head: The first node of linked list. @return: The head of linked list. """ definsertionSortList(self, head): dummy = ListNode(0) dummy.next = head cur = head while cur isnotNone: if cur.nextisnotNoneand cur.next.val < cur.val: # find insert position for smaller(cur->next) pre = dummy while pre.nextisnotNoneand pre.next.val < cur.next.val: pre = pre.next # insert cur->next after pre temp = pre.next pre.next = cur.next cur.next = cur.next.next pre.next.next = temp else: cur = cur.next return dummy.next