147 Insertion Sort List

1. Question

Sort a linked list using insertion sort.

2. Implementation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(0);
        ListNode preNode = dummy, curNode = head, nextNode = null;

        while (curNode != null) {
            nextNode = curNode.next;
            while (preNode.next != null && preNode.next.val <= curNode.val) {
                preNode = preNode.next;
            }

            curNode.next = preNode.next;
            preNode.next = curNode;
            preNode = dummy;
            curNode = nextNode;
        }
        return dummy.next;
    }
}

3. Time & Space Complexity

时间复杂度O(n^2), 空间复杂度O(1)

Last updated

Was this helpful?