【刷題劍指offer】兩個鏈表的第一個公共節點

思路:先統計出兩個鏈表的長度M和N,然後讓長鏈表先走M-N步,然後一起走,每步都比較兩個鏈表的節點是否相同,如果相同那麼跳出循環,返回第一個公共節點

代碼:

struct ListNode{
	int val;
	ListNode* next;
};
int countLength(ListNode*phead)
{
	unsigned int len = 0;
	ListNOde*pNode = phead;
	while (pNode != NULL)
	{
		pNode = pNode->next;
		len++;
	}
	return len;
}
ListNode* FindFirstNode(ListNode*phead1, ListNode*phead2)
{
	if (phead1 == NULL || phead1 == NULL)
		return NULL;
	unsigned int M = countLength(phead1);
	unsigned int N = countLength(phead2);
	int dif;
	if (M>N)
	{
		ListNode*L_long = phead1;
		ListNode*L_short = phead2;
		dif = M - N;
	}
	else
	{
		ListNode*L_long = phead2;
		ListNode*L_short = phead1;
		dif = N-M;
	}
	//先在長鏈表上走幾步,再同時在兩個鏈表上遍歷
	for (int i = 0; i < dif; i++)
		L_long = L_long->next;
	while (L_long != NULL&&L_short != NULL&&L_long != L_short)
	{
		L_long = L_long->next;
		L_short = L_short->next;
	}
	ListNode*common = L_short;
	return common;
}


發佈了44 篇原創文章 · 獲贊 3 · 訪問量 8915
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章