剑指offer——两个链表的第一个公共结点

本文介绍了一种算法,用于在两个链表中找到第一个共同节点,通过计算链表长度差并同步遍历实现。

首先计算两个链表的长度m,n,让较长的链表先走|m-n|,然后两个链表一起走,直到找到元素相同的结点。

#include <iostream>
using namespace std;

ListNode
{
	int m_data;
	ListNode *m_next;
};

unsigned int GetListLength(ListNode* pHead)
{
	unsigned int nLength=0;
	ListNode* pNode=pHead;
	while(pNode!=NULL)
	{
		++nLength;
		pNode=pNode->m_next;
	}
}

ListNode* FindFirstCommonNode(ListNode* pHead1,ListNode* pHead2)
{
	unsigned int nLength1=GetListLength(pHead1);
	unsigned int nLength2=GetListLength(pHead2);
	int nLengthDif=nLength1-nLength2;
	ListNode* pListLong=pHead1;
	ListNode* pListShort=pHead2;
	if (nLength2>nLength1)
	{
		pListLong=pHead2;
		pListShort=pHead1;
		nLengthDif=-nLengthDif;
	}
	for (int i=0;i<nLengthDif;i++)
	{
		pListLong=pListLong->m_next;
	}
	while((pListLong!=NULL)&&(pListShort!=NULL)&&(pListLong!=pListShort))
	{
		pListLong=pListLong->m_next;
		pListShort=pListShort->m_next;
	}
	ListNode* pFirstCommonNode=pListLong;
	return pFirstCommonNode;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值