首页 > 代码库 > 147. Insertion Sort List

147. Insertion Sort List

Sort a linked list using insertion sort.

思路:插入排序,就是把node插入到左边的链表中。用一个dummynode来构造左边的链表。要是比最左边的数还小,就插到最左边也就是dummy.next。如果不是,则linear search左边的链表插入。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode insertionSortList(ListNode head) {        ListNode dummy=new ListNode(-1);                while(head!=null)    {        ListNode cur=head;        head=head.next;                ListNode target=dummy;        while(target.next!=null&&target.next.val<cur.val)        {            target=target.next;;        }        cur.next=target.next;        target.next=cur;    }    return dummy.next;    }}

 

147. Insertion Sort List