遍历第一个链表,使用Set保存每个节点的值,再遍历第二遍链表,看Set中是否有相同的值。
var getIntersectionNode = function(headA, headB) {
if(!headA||!headB)return null;
let cur1 = headA,cur2 = headB;
const set = new Set();
let ans = null;
while(cur1){
set.add(cur1);
cur1 = cur1.next;
}
while(cur2){
if(set.has(cur2)){
ans = cur2;
break;
}
cur2 = cur2.next;
}
return ans;
};
双指针
var getIntersectionNode = function(headA, headB) {
if(!headA||!headB)return null;
let cur1 = headA,cur2 = headB;
while(cur1!==cur2){
cur1 = cur1 === null ? headB : cur1.next;
cur2 = cur2 === null ? headA : cur2.next;
}
return cur2;
};