剑指offer : 两条链表的第一个公共节点

题目描述:输入两个链表,找出它们的第一个公共结点。

如下图所示:两条链表如果出现公共节点,那么他们自公共节点之后的节点完全相同,,因此这两条链的结构是一个类Y型,但公共节点之前的节点却不能保证,因此我们在考虑时要进行长度的判断,然后让较长的链先走长度差个单位,然后两条链处在同一起点并行向后走,得到公共节点则返回。

class Solution
{
public:
	int GetLength(ListNode* head)
	{
		int length;
		while (head)
		{
			head = head->next;
			length++;
		}
		return length;
	}
public:
	ListNode * FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) 
	{
		if (pHead1 == nullptr)
			return nullptr;
		if (pHead2 == nullptr)
			return nullptr;
		int plength1 = GetLength(pHead1);
		int plenght2 = GetLength(pHead2);
		//计算两条链的长度差
		int diff = plength1 - plenght2;     

		ListNode* Long_one = pHead1;
		ListNode* Short_one = pHead2;
		ListNode* CommenNode;

		//如果diff小于零  说明链表1比链表2短    进行交换

		if (diff < 0)
		{
			Long_one = pHead2;
			Short_one = pHead1;
			diff = plenght2 - plength1;
		}

		//长度较长的那条链先走     先走到两条链长度相同
		for (int i = 0; i < diff; i++)
		{
			Long_one = Long_one->next;
		}

		//两条链同时向后走
		while (Long_one != nullptr&&Short_one != nullptr&&Long_one != Short_one)
		{
			Long_one = Long_one->next;
			Short_one = Short_one->next;
		}
		CommenNode = Long_one;
		return CommenNode;

	}
};

猜你喜欢

转载自blog.csdn.net/Shile975/article/details/89282365