面试题 02.07. 链表相交
1、哈希表
var getIntersectionNode = function(headA, headB) {
// 用一个哈希表存储headA中的元素
let s = new Set();
// 遍历headA中的节点,存储哈希表中,注意存储的是节点不是值,要不然会造成误会
let temp = headA
while(temp){
s.add(temp)
temp = temp.next
}
// 遍历headB,检查是否哈希表中有相同的元素(哈希表的作用)
temp = headB
while(temp){
if(s.has(temp)){
return temp
}
temp = temp.next
}
return null
};
2、双指针
var getIntersectionNode = function(headA, headB) {
let A = headA, B = headB;
while(A != B){
// headA和headB都要遍历两遍,当headA遍历完,即遇空,就开始遍历headB
// 遍历完两边之后,一定会在相交处相遇
A = A == null ? headB : A.next
B = B == null ? headA : B.next
}
return A
};