LeetCode-Python-147. 对链表进行插入排序

对链表进行插入排序。


插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

 

插入排序算法:

插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
 

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insertion-sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

第一种麻瓜思路:

转list排序再转链表。

第二种思路:

新建链表,把输入链表的每一个节点依次插入到新链表对应的位置。

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        
        dummy = ListNode(-1)
       
        cur = head
        while cur:
            tail = cur.next
            p = dummy
            while p.next and p.next.val < cur.val:
                p = p.next
                
            cur.next = p.next 
            p.next = cur
            cur = tail
            
        return dummy.next

第三种思路:

原地转换。

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        
        dummy = ListNode(-1)
        dummy.next = head
        pre = head #pre始终指着排序好链表的最后一个节点
        cur = head.next #cur始终指着未排序链表的第一个节点
        while cur:
            tail = cur.next
            pre.next = tail  #把cur这个节点拿出来
            
            p = dummy
            while p.next and p.next.val < cur.val: #找到插入的位置
                p = p.next
                
            cur.next = p.next #把cur插入到p和p.next之间
            p.next = cur
            cur = tail
            
            if p == pre:#如果刚插入到了已排序链表的末尾
                pre = pre.next #那么就更新pre
        return dummy.next

原地转换的另一种实现,写于2019年7月10日20:09:02

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        
        dummy = ListNode(-9999999999)
        dummy.next = head
        p = head
        while p:
            while p and p.next and p.val < p.next.val:
                p = p.next
            
            if not p.next:
                break
            cur = p.next
            tail = cur.next
            p.next = tail
            cur.next = None
            
            tmp = dummy
            while tmp and tmp.next and tmp.next.val < cur.val:
                tmp = tmp.next
                
            tmp2 = tmp.next
            tmp.next = cur
            cur.next = tmp2
            
            # self.printList(dummy.next)
            
        return dummy.next
        
    def printList(self, head):
        res = []
        while head:
            res.append(head.val)
            head = head.next
        print res

 

你可能感兴趣的:(Leetcode,链表)