Skip to main content

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

52. 两个链表的第一个公共节点(160. 相交链表)

输入两个链表,找出它们的第一个公共节点。

在节点 c1 开始相交。

示例

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

代码

const list1 = {
'val':4,
'next':{
'val':1,
'next':{
'val':8,
'next':{
'val':4,
'next':{
'val':5,
'next':undefined
}
}
}
}
}

const list2 = {
'val':5,
'next':{
'val':0,
'next':{
'val':8,
'next':{
'val':9,
'next':{
'val':5,
'next':undefined
}
}
}
}
}

思路:

  1. 声明数组存放链表 1 节点
  2. 声明计数器
  3. 通过计数器查看链表 2 中的值存在链表 1 的值
var getIntersectionNode = function(list1, list2) {

const arr = []

// 数组储存链表1
let current = list1;

while (current) {
arr.push(current)
current = current.next;
}
arr.push(current)

let count = 0
current = list2;

// 遍历链表2是否存在
while (current) {
if (arr[count].val === current.val) {
return current;
}
count++
current = current.next;
}

// 不存在返回 null
return null;
};

console.log(getIntersectionNode(list1,list2))