题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ #include <cstddef> class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if (pHead1 == NULL || pHead2 == NULL) { return NULL; } ListNode * pNode1 = pHead1; set<ListNode *> set_tmp; while (pNode1 != NULL) { set_tmp.insert(pNode1); pNode1 = pNode1->next; } ListNode * pNode2 = pHead2; while (pNode2 != NULL) { if (set_tmp.find(pNode2) != set_tmp.end()) { return pNode2; } pNode2 = pNode2->next; } return NULL; } };