分析:如果兩個單向鏈表有公共的結點,也就是說兩個鏈表從某一結點開始,它們的m_pNext都指向同一個結點。但由於是單向鏈表的結點,每個結點只有一個m_pNext,因此從第一個公共結點開始,之后它們所有結點都是重合的,不可能再出現分叉。所以,兩個有公共結點而部分重合的鏈表,拓撲形狀看起來像一個Y,而不可能像X。
我們先把問題簡化:如何判斷兩個單向鏈表有沒有公共結點?前面已經提到,如果兩個鏈表有一個公共結點,那么 該公共結點之后的所有結點都是重合的。那么,它們的最后一個結點必然是重合的。因此,我們判斷兩個鏈表是不是有重合的部分,只要分別遍歷兩個鏈表到最后一 個結點。如果兩個尾結點是一樣的,說明它們用重合;否則兩個鏈表沒有公共的結點。
在上面的思路中,順序遍歷兩個鏈表到尾結點的時候,我們不能保證在兩個鏈表上同時到達尾結點。這是因為兩個鏈表不一定長度一樣。但如果假設一個鏈表比另一個長l個結點,我們先在長的鏈表上遍歷l個結點,之后再同步遍歷,這個時候我們就能保證同時到達最后一個結點了。由於兩個鏈表從第一個公共結點考試到鏈表的尾結點,這一部分是重合的。因此,它們肯定也是同時到達第一公共結點的。於是在遍歷中,第一個相同的結點就是第一個公共的結點。
在這個思路中,我們先要分別遍歷兩個鏈表得到它們的長度,並求出兩個長度之差。在長的鏈表上先遍歷若干次之后,再同步遍歷兩個鏈表,知道找到相同的結點,或者一直到鏈表結束。此時,如果第一個鏈表的長度為m,第二個鏈表的長度為n,該方法的時間復雜度為O(m+n)。
基於這個思路,我們不難寫出如下的代碼:
public class FirstCommonNodeList { static class Node { int data; Node next; } public static void main(String[] args) { Node node1 = null, node2 = null; Node node = findFirstCommonNode(node1, node2); System.out.println(node); } /* * 單鏈表相交的結果為成“Y”形 */ private static Node findFirstCommonNode(Node node1, Node node2) { // 獲取鏈表的長度 int nLength1 = GetListLength(node1); int nLength2 = GetListLength(node2); // 應多走的步數 int extraLength = nLength1 - nLength1; Node pNodeLong = node1, pNodeShort = node2; if (nLength1 < nLength2) { extraLength = nLength2 - nLength1; pNodeLong = node2; pNodeShort = node1; } // 長鏈表先走extraLength步 while (extraLength > 0) { pNodeLong = pNodeLong.next; extraLength--; } Node pNodeCommon = null; // 兩個鏈表同時向后走 while (pNodeLong != null && pNodeShort != null) { pNodeLong = pNodeLong.next; pNodeShort = pNodeShort.next; if (pNodeLong == pNodeShort) { pNodeCommon = pNodeLong; break; } } return pNodeCommon; } /* * 獲取鏈表長度 */ private static int GetListLength(Node node1) { int length = 0; while (node1 != null) { length++; node1 = node1.next; } return length; } }