Friday, September 12, 2014

Leetcode: Insertion Sort List @Python

# 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 not head: return None
        nextH=ListNode(0)
        nextH.next=head
        crt=head
        while crt.next:
            if crt.next.val>=crt.val:
                crt=crt.next
                continue
            cmpr=nextH.next
            last=nextH
            while crt.next.val>cmpr.val:
                last=cmpr
                cmpr=cmpr.next
            temp=crt.next.next
            last.next=crt.next
            crt.next.next=cmpr
            crt.next=temp
        return nextH.next

No comments :

Post a Comment