Write a PRogram to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory.
s思路: 1. 這道題確實做過,印象深刻。通過做輔助線,把問題轉換成熟悉的問題,再用熟悉的配方來解決。假設有兩條鏈表A,B,我們先遍歷A到A的結尾然后把A的尾巴指向A的頭部,這樣一來,就有一個cycle,如果我們再從B開始用快慢指針大法去檢測這個cycle,并找到cycle所在的地方,就是兩條鏈表的intersection 開始的地方。如果AB沒有intersection,那么我們遍歷B就不會遇到cycle。
新聞熱點
疑難解答