题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
双指针交换循环需要加一个计数器,否则可能死循环
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if(!pHead1 || !pHead2) return NULL; ListNode *p1 = pHead1, *p2 = pHead2; int cnt = 0; while(p1 != p2) { p1 = p1->next; p2 = p2->next; if(p1 == p2) return p1; if(!p1) { p1 = pHead2; cnt++; } if(!p2) p2 = pHead1; if(cnt == 2) return NULL; } return p1; } };