A 17-line solution, without using extra space [JavaScript]


  • 0
    H
    var beforeHead = { next: head };
    var insertPosition = beforeHead, prev = beforeHead, node = head;
    while (node) {
        var next = node.next;
        if (node.val < x) {
            if (insertPosition.next !== node) {
                prev.next = next;
                node.next = insertPosition.next;
                insertPosition.next = node;
            }
            insertPosition = node;
        } else {
            prev = node;
        }
        node = next;
    }
    return beforeHead.next;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.