题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
#include <stdio.h>
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
if(pHead1 == NULL || pHead2 == NULL)
return NULL;
struct ListNode *p1=pHead1;
struct ListNode *p2=pHead2;
while(p1 != p2)
{
// 如果 p1 到达了链表尾部,则指向 pHead2,否则继续向后移动
p1 = (p1 == NULL) ? pHead2 : p1->next;
// 如果 p2 到达了链表尾部,则指向 pHead1,否则继续向后移动
p2 = (p2 == NULL) ? pHead1 : p2->next;
}
return p2;
}
这种写法也行,相同的原理
