ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
{
ListNode* p1 = pHead1;
ListNode* p2 = pHead2;
int len1 = 0;
int len2 = 0;
int diff;
while(p1)
{
len1++;
p1 = p1->next;
}
while(p2)
{
len2++;
p2 = p2->next;
}
if (len1 >len2)
{
diff = len1 - len2;
p1 = pHead1;
p2 = pHead2;
}
else
{
diff = len2 - len1;
p1 = pHead2;
p2 = pHead1;
}
for (int i = 0; i < diff; i++)
{
p1 = p1->next;
}
//链表的访问用 while 循环来完成
//p = p->next;
//结束条件判断最后一个节点是否为空
//p1 != NULL && p2 != NULL
//两个链表同时访问
while(p1 != NULL && p2 != NULL)
{
if (p1 == p2)
{
break;
}
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
关于单链表 访问的思考
最新推荐文章于 2023-10-02 20:41:16 发布