题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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 nullptr; } ListNode* p1 = pHead1; ListNode* p2 = pHead2; while (p1 && p2) { if (p1 == p2) { return p1; } p1 = p1->next; p2 = p2->next; } if (p1) { ListNode* new_p1 = pHead1; while (p1) { new_p1 = new_p1->next; p1 = p1->next; } ListNode* new_p2 = pHead2; while (new_p1 && new_p2) { if (new_p1 == new_p2) { return new_p1; } new_p1 = new_p1->next; new_p2 = new_p2->next; } } if (p2) { ListNode* new_p2 = pHead2; while (new_p2 && p2) { new_p2 = new_p2->next; p2 = p2->next; } ListNode* new_p1 = pHead1; while (new_p1 && new_p2) { if (new_p1 == new_p2) { return new_p1; } new_p1 = new_p1->next; new_p2 = new_p2->next; } } return nullptr; } };