Insertion Sort List

Sort a linked list using insertion sort.

Example

Given 1->3->2->0->null, return 0->1->2->3->null.

Solution

dummy里面是已经拍好序的,

head 是即将排序的,head 对比dummy 找到合适的位置插入。

"""
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):
        dummy = ListNode(0)
        while head:
            node = dummy 
            while node.next and node.next.val < head.val:
                node = node.next
            temp = head.next
            head.next = node.next # insert head.next value into the middle
            node.next = head # linked node pointed to the middle node
            head = temp

        return dummy.next

Last updated

Was this helpful?