147. Insertion Sort List

 

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;
    }
}

 

posted @ 2017-10-15 10:54  乐乐章  阅读(138)  评论(0编辑  收藏  举报