JSFiddle - React, Tailwind, and code Playground

by Fareez Ahmed

JavaScript

var LinkedList = function () {
    this.head = null;
    this.tail = null;
};

LinkedList.prototype.makeNode = function (val) {
    var node = {};
    node.val = val;
    node.next = null;
    return node;
};

LinkedList.prototype.getLength = function (head) {
    var length = 0;
    if (!head) {
        return 0;
    }

    while (head) {
        length++;
        head = head.next;
    }
    return length;
};

LinkedList.prototype.advanceToKthNode = function (LL, k) {
    var current = LL.head;

    while (k > 0 && current !== null) {
        current = current.next;
        k--;
    }

    return current;
};
LinkedList.prototype.isIntersection = function (LL1, LL2) {
    var tail1 = LL1.tail;
    var tail2 = LL2.tail;
    var length1 = LL1.getLength(LL1.head);
    var length2 = LL2.getLength(LL2.head);

    if (tail1.val !== tail2.val) {

        return false;
    }

    var shorter = ((length1 > length2) ? LL2 : LL1);

    var longer = ((length1 > length2) ? LL1 : LL2);

    var difference = Math.abs(length1 - length2);

    if (difference > 0) {

        //advance the longer one if there's a difference. this works.
        longer = this.advanceToKthNode(longer, difference);
        console.log(longer)

    }

    //point to the heads so you can iterate.
    var shortIterator = shorter.head;
    // this dosn't have a head if you advanced it.
    var longIterator = longer.head || longer.val;

    console.log(longIterator);
    // console.log(shortIterator);
    var intersection = "No Intersection";
    //don't count the tail as an intersection.
    while (longIterator && shortIterator && (longIterator !== longer.tail)) {
        console.log("LONG", longIterator)
        console.log("SHORT", shortIterator)
        if (longIterator.val === shortIterator.val) {
            intersection = longIterator.val;
        }
        shortIterator = shortIterator.next;
        longIterator = longIterator.next;
    }

    // while ((longIterator &&...