147 Insertion Sort List 链表插入排序

用插入排序对链表进行排序。

详见:https://leetcode.com/problems/insertion-sort-list/description/

Java实现:

链表的插入排序实现原理很简单,就是一个元素一个元素的从原链表中取出来,然后按顺序插入到新链表中,时间复杂度为O(n2),是一种效率并不是很高的算法,但是空间复杂度为O(1),以高时间复杂度换取了低空间复杂度。

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

 

posted on 2018-04-06 12:53  lina2014  阅读(147)  评论(0编辑  收藏  举报

导航