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(-1);
    while(head != null) {
        ListNode p = dummy;
        while(p.next != null && p.next.val < head.val) {
            p = p.next;
        }
        ListNode post = head.next;
        head.next = p.next;
        p.next = head;
        head = post;
    }
    return dummy.next;
}

results matching ""

    No results matching ""