1. 程式人生 > >判斷兩個單鏈表是否相交,若相交,求節點(連結串列不帶環)

判斷兩個單鏈表是否相交,若相交,求節點(連結串列不帶環)

先理解一下題目的意思,單鏈表的相交和普通兩條線的相交一樣嗎? 在這裡插入圖片描述 所以當我們把其換成節點就可以變成下面這樣:

在這裡插入圖片描述 先判斷連結串列是否相交,我們可以運用兩個連結串列相交後就變成了一條連結串列這個特性來判斷,因為如果兩條連結串列相交,那麼這兩條連結串列的最後一個節點一定是同一個節點,否則不可能相交

	//1表示有交點,0表示沒有交點
	int IsIntersection(Node *first1, Node *first2)
	{
		assert(first1);
		assert(first2);
		while (first1->next != NULL)
		{
			first1 = first1->next;
		}
		while (first2->next != NULL)
		{
			first2 = first2->next;
		}
		if (first1 == first2)
		{
			return 1;
		}
		return 0;
	}

接下來,我們考慮交點的問題,如何才能找到交點? 兩條連結串列在交點之後的長度肯定是一樣的,在交點之前的長度是不一樣的,我們可以計算出兩條連結串列長度的差值k,然後讓長的連結串列先走k步,再讓兩條連結串列同時走,當相同的時候,就表示走到交點了,這時候返回即可 在這裡插入圖片描述

	int GetLength(Node *first)
	{
		assert(first);
		int count = 0;
		while (first != NULL)
		{
			count++;
			first = first->next;
		}
		return count;
	}

	Node *IntersectionNode(Node *first1, Node *first2)
	{
		assert(first1);
		assert(first2);
		int count1 = GetLength(first1);
		int count2 = GetLength(first2);
		Node *longer = first1;
		Node *shorter = first2;
		int k = count1 - count2;
		if (count1 < count2)
		{
			longer = first2;
			shorter = first1;
			k = count2 - count1;
		}
		while (k--)
		{
			longer = longer->next;
		}
		while (longer != shorter)
		{
			longer = longer->next;
			shorter = shorter->next;
		}
		return longer;
	}