1. 程式人生 > >Lintcode380 Intersection of Two Linked Lists solution 題解

Lintcode380 Intersection of Two Linked Lists solution 題解

AI sin tro ans 答案 which fun ins 我們

【題目描述】

Write a program to find the node at which the intersection of two singly linked lists begins.

Notice:

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.

請寫一個程序,找到兩個單鏈表最開始的交叉節點。

【註】1、如果兩個鏈表沒有交叉,返回null。

2、在返回結果後,兩個鏈表仍須保持原有的結構。

3、可假定整個鏈表結構中沒有循環。

【題目鏈接】

www.lintcode.com/en/problem/intersection-of-two-linked-lists/

【題目解析】

這道題可以使用雙指針法。

維護兩個指針pA和pB,初始分別指向A和B。然後讓它們分別遍歷整個鏈表,每步一個節點。

當pA到達鏈表末尾時,讓它指向B的頭節點(沒錯,是B);類似的當pB到達鏈表末尾時,重新指向A的頭節點。

如果pA在某一點與pB相遇,則pA/pB就是交點。

下面來看下為什麽這個算法可行,考慮兩個鏈表:A = {1,3,5,7,9,11} B = {2,4,9,11},它們的交點是節點‘9‘。由於B的長度是4 小於 A的長度6,pB會首先到達鏈表的末尾,由於pB比pA恰好少走2個節點。通過把pB指向A的頭,把pA指向B的頭,我們現在讓pB比pA恰好多走2個節點。所以在第二輪,它們可以保證同時在交點相遇。

如果兩個鏈表有交點,則它們的最後一個節點一定是同一個節點。所以當pA/pB到達鏈表末尾時,分別記錄下A和B的最後一個節點。如果兩個鏈表的末尾節點不一致,說明兩個鏈表沒有交點。

【參考答案】

www.jiuzhang.com/solutions/intersection-of-two-linked-lists/

Lintcode380 Intersection of Two Linked Lists solution 題解