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

    Sort a linked list using insertion sort.

    A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
    With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

     

    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.


    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
    class Solution {
        public ListNode insertionSortList(ListNode head) {
            if(head == null) return null;
            ListNode fakehead = new ListNode(-1);
            ListNode pre = fakehead;
            ListNode cur = head;
            while(cur != null){
                while(pre.next != null && pre.next.val < cur.val){
                    pre = pre.next;
                }
                //保存cur.next然后断掉list
                ListNode next = cur.next;
                cur.next = pre.next;
                pre.next = cur;
                cur = next;
                pre = fakehead;
            }
            return fakehead.next;
        }
    }

    定义一个cur结点,从head开始向后,相当于外循环;一个pre结点,用while寻找该插入的位置,最后找到之后,把cur接进pre和pre.next之间,相当于内循环,但是这个内循环是从前往后的。注意,这里仍然没有用到swap,而是结点的插入。链表不存在坑位平移的问题,想插入一个node只需要拼接首位就行了。仍要注意,在拼接cur节点之前,要把cur.next保存起来,才能找到下一个cur的位置。

    https://www.jianshu.com/p/602ddd511d37

  • 相关阅读:
    RedisUtil
    CSS基础知识点笔记
    fdgfgfgfgf
    PerfMon Metrics Collector插件的Disks I/O使用总结
    Jmeter使用笔记之html报告扩展(一)
    Jmeter使用笔记之意料之外的
    Jmeter使用笔记之函数
    Jmeter使用笔记之组件的作用域
    css 初始化文件 全面
    vue-grid-layout 使用以及各项参数作用
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11470740.html
Copyright © 2011-2022 走看看