码迷,mamicode.com
首页 > 其他好文 > 详细

147. Insertion Sort List

时间:2017-10-15 14:12:44      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:class   logs   blank   ane   esc   col   next   ons   reac   

 

Sort a linked list using insertion sort.

 

这道题其实主要考察链表的基本操作,用到的小技巧也就是在Swap Nodes in Pairs中提到的用一个辅助指针来做表头避免处理改变head的时候的边界情况。

helper先不和head相连,也是个边界

 

class Solution {   //难需要背过
    public ListNode insertionSortList(ListNode head) {
        if(head==null || head.next == null) return head;
        ListNode cur = head;
        ListNode sorted = new ListNode(0);
        ListNode pre = sorted;
        ListNode next = null;
        while(cur!=null){
            next = cur.next;
            while(pre.next!=null && pre.next.val < cur.val)
                pre = pre.next;
            cur.next = pre.next;
            pre.next = cur;
            pre = sorted;
            cur = next;
        }
        return sorted.next;
    }
}

 

147. Insertion Sort List

标签:class   logs   blank   ane   esc   col   next   ons   reac   

原文地址:http://www.cnblogs.com/zle1992/p/7670222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!