Friday, November 6, 2015

[leetcode]Insertion Sort of List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        dummy.next = head;
        while (head != null){
            ListNode next = head.next;
            ListNode previous = dummy;
            ListNode current = previous.next;
            head.next = null;
            while (current != null && head.val > current.val){
                previous = current;
                current = current.next;
            }
            if (current != head){
                previous.next = head;
                head.next = current;
            }
            head = next;
        }

        return dummy.next;        
    }
}

No comments:

Post a Comment