Leetcode 92: Reverse Linked List II

Nov. 4, 2021

Here is my leetcode solution in JavaScript:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function(head, left, right) {
    let currPos = 1;
    let currNode = head;
    let startNode = head;
    let endNode = null;

    while(currPos < left) {
        startNode = currNode;
        currNode = currNode.next;
        currPos++;
    }

    let newList = null;
    let tail = currNode;

    while (currPos <= right) {
        const next = currNode.next;
        currNode.next = newList;
        newList = currNode;
        currNode = next;
        currPos++;
    }

    startNode.next = newList;
    tail.next = currNode;

    if (left > 1) {
        return head;
    }

    return newList;


};

Link to problem.