c/c++單鏈表面試題—鏈表相交問題

一、判斷兩個單鏈表是否是相交
ide

思路分析:對象

最簡單直接的方法就是依次遍歷兩條鏈表,判斷其尾節點是否是相等,相等則相交不然不相交。it

bool CheckCross(const List& list1, const List& list2)//list1,list2爲兩個對象
{
	Node* l1 = list1._head;
	Node* l2 = list2._head;
	while (l1->_next)//找到list1的尾節點
	{
		l1 = l1->_next;
	}
	while (l2->_next)//找到list2的尾節點
	{
		l2 = l2->_next;
	}
	if (l1 == l2)
	{
		return true;//相交
	}
	return false;//不相交
}

二、找到兩個單鏈表的交點ast

思路分析:class

在兩個單鏈表長度相等的狀況下是最簡單的,只須要同時遍歷兩個鏈表而且不斷地比較,若是相等則爲交點不然不是交點。可是在兩條單鏈表長度不相等的狀況下,則能夠讓長度較長的鏈表先遍歷兩條鏈表的長度之差,而後再同時遍歷既可。List

Node* GetCrossNode(List& list1, List& list2)
{
	int length1 = list1.GetListLength();//求list1的長度
	int length2 = list2.GetListLength();//求list2的長度
	int diff = 0;
	Node* slow = NULL;
	Node* fast = NULL;
	if (length1 > length2)//list1的長度比list2的長度要長
	{
		diff = length1 - length2;//單鏈表的長度之差
		fast = list1._head;
		slow = list2._head;
		while (diff--)
		{
			fast = fast->_next;
		}
		while (fast&&slow)
		{
			if (fast == slow)
			{
				return slow;//返回交點
			}
			fast = fast->_next;
			slow = slow->_next;
		}
	}
	else                                 //list2的長度比list1的長度要長
	{
		diff = length1 - length2;
		fast = list2._head;
		slow = list1._head;
		while (diff--)
		{
			fast = fast->_next;
		}
		while (fast&&slow)
		{
			if (fast == slow)
			{
				return slow;//返回交點
			}
			fast = fast->_next;
			slow = slow->_next;
		}
	}
	return NULL;//不相交
}

int  List::GetListLength()//求取單鏈表長度的方法
{
	int count = 0;
	Node* cur = _head;
	while (cur)
	{
		count++;
		cur = cur->_next;
	}
	return count;
}
相關文章
相關標籤/搜索