Categories
Leetcode

Reverse Middle of LinkedList

// m = start of items to reverse, n = end of item to reverse
let reverseBetween = function(head, m, n) {

    let node = head,
        result = [],
        reversed = [],
        counter = 1;

    while (node) {
        let next = node.next;
        if (counter < m) {
            result.push(node); //?
        }
        if (counter >=m && counter <= n) {
            node.next = null;
            reversed.push(node); //?
        }
        else if (counter > n) {
            // all reversals are done
            // drain reversed into result
            while (reversed.length) {
                result.push(reversed.pop()); //?
            }
            result.push(node);
            break;
        }

        counter++;
        node = next;
    }

    // if reversals are done at the end of the linkedlist
    while (reversed.length) {
        result.push(reversed.pop()); //?
    }

    let root = new ListNode(0), tail = root;
    while (result.length) {
        tail.next = result.shift();
        tail = tail.next;
        console.log(tail);
    }

    return root.next; //?
};

Leave a Reply

Your email address will not be published. Required fields are marked *