/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* p=pHead1;
struct ListNode* q=pHead2;
int i=0;
if(p==NULL || q==NULL)
return NULL;
//循环之前需要确保两个链表不为空
while(i!=2) //一共遍历两次,目的为了使两个变量都分别遍历过两个链表,使其所经过的路程一样
{
if(p==q)
return p;
p=p->next;
q=q->next;
if(p==NULL) //p将p所表示的链表遍历完成后,从另一个链表的头节点开始遍历
{
p=pHead2;
i++;
}
if(q==NULL)
{
q=pHead1;
}
}
return NULL;
}