两个链表的第一个公共结点

给定两个单链表的头节点 headA 和 headB ,请找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

图示两个链表在节点 c1 开始相交:

思路和算法

  • 判断两个链表是否相交,可以使用哈希集合存储链表节点。
  • 首先遍历链表 headA,并将链表 headA 中的每个节点加入哈希集合中。然后遍历链表 headB,对于遍历到的每个节点,判断该节点是否在哈希集合中:
  • 如果当前节点不在哈希集合中,则继续遍历下一个节点;
  • 如果当前节点在哈希集合中,则后面的节点都在哈希集合中,即从当前节点开始的所有节点都在两个链表的相交部分,因此在链表 \textit{headB}headB 中遍历到的第一个在哈希集合中的节点就是两个链表相交的节点,返回该节点。

如果链表 \textit{headB}headB 中的所有节点都不在哈希集合中,则两个链表不相交,返回 \text{null}null。

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/3u1WK4/solution/liang-ge-lian-biao-de-di-yi-ge-zhong-he-0msfg/
来源:力扣(LeetCode)

function ListNode(x){
    this.val = x;
    this.next = null;
}
function FindFirstCommonNode(pHead1, pHead2)
{
    // write code here
    const visited=new Set();
    let temp=pHead1;
    while (temp){
        visited.add(temp);
        temp=temp.next;
    }
    temp=pHead2;
    while(temp){
        if(visited.has(temp)){
            return temp;
        }
        temp=temp.next;
    }
    return null;


}
module.exports = {
    FindFirstCommonNode : FindFirstCommonNode
};
阅读剩余
THE END