首页 > 其他 > 详细

147. Insertion Sort List

时间:2017-10-15 12:35:37      阅读:220      评论:0      收藏:0      [点我收藏+]

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!