编写一个程序,找到两个单链表相交的起始节点
思路:
方法一:哈希表
1.遍历链表A,将其节点放入哈希表中
2.遍历链表B,如果哈希表中存在链表B的元素,返回该元素
方法二:双指针
1.指针1指向headA,指针2指向headB
2.指针1遍历完headA,重定位到headB
指针2遍历完headB,重定位到headA
3.如果两者相同,则说明必有相交处(PA + AC + PB = PB + AC + PA)
var getIntersectionNode = function(headA, headB) {
//方法一:哈希表
let map = new Map()
let current = headA
while(current){
map.set(current,1)
current = current.next
}
current = headB
while(current){
if(map.has(current)){
return current
}
current = current.next
}
return null
//方法二:双指针
if(headA == null || headB == null) return null
let p = headA
let q = headB
while(p!==q){
p= p==null ? headB:p.next
q= q==null ? headA:q.next
}
return p
};