//两个单链表有公共节点,那么公共节点一定出现在两个链表的尾部。
//从两个链表的尾部向前比较,最后一个相同的节点就是我们要找的节点。
//方法1:用“先进后出”的想法——栈来实现。把两个链表的节点放入两个栈中,依次弹出比较两个栈顶节点是否相同。
//方法2:链表的长度不同时,从头开始遍历到尾节点的时间就会不同。
//首先遍历两个链表的长度,得到长的链表比短的链表多n个节点。
//然后第二次遍历时,在较长的链表上先走n步,然后两个链表同时遍历,找到第一个相同的节点就是第一个公共节点
#include<iostream>
using namespace std;
struct ListNode
{
int value;
ListNode * next;
};
int GetLength(ListNode* pHead)
{
int count = 0;
while (pHead != NULL)
{
count++;
pHead = pHead->next;
}
return count;
}
ListNode* FindFirstCom(ListNode* p1, ListNode* p2)
{
ListNode * pLong;
ListNode* pShort;
int len1 = GetLength(p1);
int len2 = GetLength(p2);
int m = len1-len2;
if (m>0)
{
pLong = p1;
pShort = p2;
}
else
{
pLong = p2;
pShort = p1;
m = -m;
}
for (int i = 0; i < m; i++)
pLong = pLong->next;
while (pLong != NULL && pShort != NULL && pLong != pShort)
{
pLong = pLong->next;
pShort = pShort->next;
}
return pShort;
}
链表的第一个公共节点
最新推荐文章于 2022-08-08 11:26:19 发布