编写一个程序,找到两个单链表相交的起始节点
思路:
方法一:哈希表
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
};
本文介绍了如何使用哈希表和双指针技巧来解决单链表相交问题。通过哈希表存储链表A节点,双指针同时遍历链表A和B,一旦发现重复元素即为相交节点。两种方法对比实用场景和效率。
539

被折叠的 条评论
为什么被折叠?



