Categories
Leetcode Loop

LinkedList Palindrome

let isPalindrome = function(head) {

let slow = head, fast = head, val = [slow.val];

while (fast.next) {
if (fast.next.next) {
fast = fast.next.next;
slow = slow.next;
val.push(slow.val);
}
else {
fast = fast.next;
slow = slow.next;
}
}

while (slow) {
if (slow.val !== val.pop()) {
return false;
}
slow = slow.next;
}

return val.length === 0;
};
Categories
Leetcode

LinkedList Middle Node

let middleNode = function(head) {
    let slow = head, fast = head;
    while (fast) {
        if (fast.next !== null && fast.next.next !== null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        else if (fast.next) {
            slow = slow.next;
            break;
        }
        else {
            break;
        }
    }
    return slow;
};
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; //?
};
Categories
Leetcode

Reverse LinkedList (Iterative)

let reverseLinkedList = function(root) {

    let reverse = new ListNode(0);

    let node = root;
    while (node) {
        let toAdd = node;
        let next = node.next;

        let reversedNext = reverse.next;
        toAdd.next = reversedNext;
        reverse.next = toAdd; //

        node = next;
    }
    return reverse.next;
}
Categories
Leetcode Recursion

Reverse LinkedList (Recursion)

let reverseLinkedList = function(root, reverse = new ListNode(0)) {
if (root) {
let toAdd = root;
let next = root.next;

let reversedNext = reverse.next;
toAdd.next = reversedNext;
reverse.next = toAdd;

reverseLinkedList(next, reverse);
}
return reverse.next;
}