Skip to main content

Leetcode - 160. Intersection of Two Linked Lists

· One min read

https://leetcode.com/problems/intersection-of-two-linked-lists/

Solution 1

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function (headA, headB) {
if (!headA || !headB) {
return null;
}

let nodeA = headA;
let nodeB = headB;

while (nodeA !== nodeB) {
nodeA = nodeA.next;
nodeB = nodeB.next;

console.log(nodeA, nodeB);

if (nodeA === nodeB) {
return nodeA;
}

if (!nodeA) {
nodeA = headB;
}
if (!nodeB) {
nodeB = headA;
}
}

return nodeA;
};