python leetcode 147. Insertion Sort List

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        p=head
        mystack=[p]
        p=p.next
        while p:
            q=p.next
            p.next=None
            if mystack[-1].val<=p.val:
                mystack[-1].next=p
                mystack.append(p)
            else:
                for i in range(len(mystack)):
                    if p.val <= mystack[i].val:
                        p.next=mystack[i]
                        if i>0:
                            mystack[i-1].next=p 
                        mystack.insert(i,p) 
                        break
            p=q
        mystack[-1].next=None 
        return mystack[0]

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84998066