zoukankan      html  css  js  c++  java
  • Leetcode 147. Insertion Sort List

    Description: Sort a linked list using insertion sort.

    Algorithm of Insertion Sort:

    1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
    2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
    3. It repeats until no input elements remain.

    Link: https://leetcode.com/problems/insertion-sort-list/

    Examples:

    Example 1:
    Input: 4->2->1->3
    Output: 1->2->3->4
    
    Example 2:
    Input: -1->5->3->4->0
    Output: -1->0->3->4->5

    思路: 依照插入排序的方法,两层循环,外层遍历没有排序的节点,内层寻找该节点的位置,即从头遍历已排序的部分,直到值大于当前节点的值,连接到其前面的节点pre上。

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

    日期: 2020-11-28 加油呀!

  • 相关阅读:
    Expect学习笔记(1)
    Awk 实例,第 3 部分
    ELF文件格式(中文版)
    sed 实例,第 1 部分
    Expect 教程中文版
    csc工具一般使用说明zz
    Microsoft Office Word 2010(zz)
    记录XPO查询 日志
    C#中判断文件或文件夹是否存在
    Discuz数据库结构1
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14052304.html
Copyright © 2011-2022 走看看