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

posted @ 2019-09-06 02:15  Schwifty  阅读(155)  评论(0编辑  收藏  举报