linked list
easy
leetcode
Given the heads of two singly linked-lists headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.
For example, the following two linked lists begin to intersect at node c1
:
Note that the linked lists must retain their original structure after the function returns
Custom Judge:
The inputs to the judge are given as follows (your program is not given these inputs):
intersectVal
- The value of the node where the intersection occurs. This is 0 if there is no intersected node.listA
- The first linked list.listB
- The second linked list.skipA
- The number of nodes to skip ahead in listA
(starting from the head) to get to the intersected node.skipB
- The number of nodes to skip ahead in listB
(starting from the head) to get to the intersected node.The judge will then create the linked structure based on these inputs and pass the two heads, headA
and headB
to your program. If you correctly return the intersected node, then your solution will be accepted.
intersectVal == listA[skipA] == listB[skipB]
if listA
and listB
intersect.Could you write a solution that runs in O(m + n)
time and use only O(1)
memory?
none.
(示意圖)
直觀的做法:把 A 的 node 存起來,遍歷 B 找重複的點
直觀的做法:既然 B 比 A 長,那就讓 B 從 b2 開始判斷。
計算 A, B 的總長,取差值
B - A
,loop 找出 c1
如果 A 和 B 同時從頭開始尋找相交的點,會在什麼時候找到 c1
list 不斷重複自己
在 A 重複自己四次、B 重複自己三次後,找到 c1 了
有發現什麼有趣的現象嗎?
從 Thinking 3 可以發現,出現相交的點後,A 和 B 最後的長度會一樣長。
還有其他方法可以讓兩者的長度一樣嗎?
A + B = B + A
Could you write a solution that runs in O(m + n)
time and use only O(1)
memory?