topic
Given the head nodes headA and headB of two singly linked lists, please find and return the starting node where the two singly linked lists intersect. Returns null if the two linked lists do not have intersecting nodes.
The title data ensures that there are no cycles in the entire chain structure.
Note that the linked list must retain its original structure after the function returns the result.
输入: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 个节点。
hash table
The simplest idea is to traverse the linked list A and store each node in a dictionary (hash table).
Then traverse dictionary B to see if the current node of B is in the dictionary. If it exists, it is an intersecting node.
double pointer
Define two pointers A and B, and start traversing from their respective linked list headers,
If the nodes pointed to by the two pointers are different, continue to move backwards
If the nodes pointed to by the two pointers are the same, an intersecting node is found, including two disjoint linked lists, both pointers will eventually move to the None pointed to by the tail node, and None will also be returned.
When a pointer moves to the end of the linked list, jump to the head of another linked list to start traversing. This ensures that two asymmetric intersecting linked lists can always move to the intersecting node at the same time after the pointer is moved.
def getIntersectionNode(headA,headB):
if not headA or not headB:
return None
A,B = headA,headB
while A!=B:
A = A.next if A else headB
B = B.next if B else headA
return A
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。