160. Intersecting Linked List
Given the head nodes headA
and of two singly linked lists headB
, please find and return the starting node where the two singly linked lists intersect. If there is no intersecting node between the two linked lists, return null
.
c1
The illustration shows that two linked lists intersect at node **:**
The title data guarantees that there are no loops in the entire chain structure.
Note that the linked list must maintain its original structure after the function returns the result .
Custom Reviews:
The inputs to the evaluation system are as follows (the program you design does not apply to this input):
intersectVal
- The value of the starting node of the intersection. If no intersecting nodes exist, this value is0
listA
- the first linked listlistB
- the second linked listskipA
-listA
the number of nodes to jump to the intersection node in (starting from the head node)skipB
-listB
the number of nodes to jump to the intersection node in (starting from the head node)
The profiling system will create a chained data structure from these inputs and pass the two head nodes headA
and headB
to your program. If the program correctly returns the intersection nodes, then your solution will be considered the correct answer .
Example 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at '8'
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,6,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
— 请注意相交节点的值不为 1,因为在链表 A 和链表 B 之中值为 1 的节点 (A 中第二个节点和 B 中第三个节点) 是不同的节点。换句话说,它们在内存中指向两个不同的位置,而链表 A 和链表 B 中值为 8 的节点 (A 中第三个节点,B 中第四个节点) 在内存中指向相同的位置。
Example 2:
输入:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Intersected at '2'
解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [1,9,1,2,4],链表 B 为 [3,2,4]。
在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
Example 3:
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。
由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
这两个链表不相交,因此返回 null 。
hint:
listA
The number of nodes inm
listB
The number of nodes inn
1 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
- If
listA
andlistB
have no intersection,intersectVal
for0
- If
listA
andlistB
have an intersection,intersectVal == listA[skipA] == listB[skipB]
problem solving ideas
double pointer linked list
Learning ideas:
- [LeetCode Daily Question] 160. Intersecting linked list | Handwritten graphic version of ideas + code explanation
- Leetcode 160. Intersecting linked list
Code
var getIntersectionNode = function(headA, headB) {
let aNode=headA,bNode=headB;
while(aNode!=bNode){
aNode=aNode?aNode.next:headB;
bNode=bNode?bNode.next:headA;
}
return aNode;
};