美文网首页
147. Insertion Sort List

147. Insertion Sort List

作者: April63 | 来源:发表于2018-06-19 22:16 被阅读0次

    插入结点 但是 超时了。。

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def insertionSortList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head or not head.next:
                return head
            dummy = ListNode(0)
            dummy.next = ListNode(head.val)
            p = head.next
            while p:
                m = p.next
                q = dummy
                while q.next and p.val > q.next.val:
                    q = q.next
                p.next = q.next
                q.next = p
                p = m
            return dummy.next    
    

    嗯 很蠢的做法

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def insertionSortList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head or not head.next:
                return head
            stack = []
            p = head
            while p:
                stack.append(p.val)
                p = p.next
            stack.sort()
            dummy = ListNode(0)
            q = dummy
            while stack:
                q.next = ListNode(stack.pop(0))
                q = q.next
            return dummy.next
    

    不超时的做法:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def insertionSortList(self, head):
            p = dummy = ListNode(0)
            cur = dummy.next = head
            while cur and cur.next:
                val = cur.next.val
                if cur.val < val:
                    cur = cur.next
                    continue
                if p.next.val > val:
                    p = dummy
                while p.next.val < val:
                    p = p.next
                new = cur.next
                cur.next = new.next
                new.next = p.next
                p.next = new
            return dummy.next
    

    相关文章

      网友评论

          本文标题:147. Insertion Sort List

          本文链接:https://www.haomeiwen.com/subject/umvzeftx.html