輸入兩個鏈表,找出他們的第一個公共節點

分析:若是兩個單向鏈表有公共的結點,也就是說兩個鏈表從某一結點開始,它們的m_pNext都指向同一個結點。但因爲是單向鏈表的結點,每一個結點只有一個m_pNext,所以從第一個公共結點開始,以後它們全部結點都是重合的,不可能再出現分叉。因此,兩個有公共結點而部分重合的鏈表,拓撲形狀看起來像一個Y,而不可能像X。java

咱們先把問題簡化:如何判斷兩個單向鏈表有沒有公共結點?前面已經提到,若是兩個鏈表有一個公共結點,那麼 該公共結點以後的全部結點都是重合的。那麼,它們的最後一個結點必然是重合的。所以,咱們判斷兩個鏈表是否是有重合的部分,只要分別遍歷兩個鏈表到最後一 個結點。若是兩個尾結點是同樣的,說明它們用重合;不然兩個鏈表沒有公共的結點。node

在上面的思路中,順序遍歷兩個鏈表到尾結點的時候,咱們不能保證在兩個鏈表上同時到達尾結點。這是由於兩個鏈表不必定長度同樣。但若是假設一個鏈表比另外一個長l個結點,咱們先在長的鏈表上遍歷l個結點,以後再同步遍歷,這個時候咱們就能保證同時到達最後一個結點了。因爲兩個鏈表從第一個公共結點考試到鏈表的尾結點,這一部分是重合的。所以,它們確定也是同時到達第一公共結點的。因而在遍歷中,第一個相同的結點就是第一個公共的結點。spa

在這個思路中,咱們先要分別遍歷兩個鏈表獲得它們的長度,並求出兩個長度之差。在長的鏈表上先遍歷若干次以後,再同步遍歷兩個鏈表,知道找到相同的結點,或者一直到鏈表結束。此時,若是第一個鏈表的長度爲m,第二個鏈表的長度爲n,該方法的時間複雜度爲O(m+n)。blog

基於這個思路,咱們不難寫出以下的代碼:同步

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;
	}
}
相關文章
相關標籤/搜索