LeetCode 92. Reverse Linked List II

I copied solution for Reverse Linked List II from this Udemy course. It was a little hard to understand all these pointers in second loop, I had to use pen and paper to draw each step to finally understand how each pointer works.

/**
 * 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;


};
Published on

Previous post: LeetCode 206. Reverse Linked List

Next post: What do you want to be when you grow up