2014年9月30日星期二

[Leetcode] Insertion Sort List

Sort a linked list using insertion sort.
比较简单的题,比较容易实现,按照插入排序的形式写就好了。


public ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        ListNode temp1 = dummy, temp2 = head, temp3 = head;
        
        while(temp2 != null) {
            temp1 = dummy; temp3 = temp2.next;
            while(temp1.next != null && temp1.next.val < temp2.val) {
                temp1 = temp1.next;
            }
            temp2.next = temp1.next;
            temp1.next = temp2;
            temp2 = temp3;
        }
        
        return dummy.next;
    }

没有评论:

发表评论