【刷题剑指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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章