• 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

  • 相关阅读:
    Mac上的常用软件
    Mac上在iterm2中使用ls时,出现Operation not permitted
    Typora常用操作
    Mac上的qemusystemaarch64占用太多内存
    软件质量管理总结
    postgres使用记录
    Linux 包含中文字符的文件名无法使用shell 选中或复制
    常见硬件知识
    iterm2 常用操作
    C# 通过 HTTPModule 防范 DOS
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11470740.html
Copyright © 2020-2023  润新知