题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
利用set容器不可以插入重复元素的特点,先插入一个链表,设置一个计数器num,如果插入第二个链表元素时链表长度不变则为公共结点
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { set<ListNode*> s; while(pHead1){ s.insert(pHead1); pHead1=pHead1->next; } int num=s.size(); while(pHead2){ s.insert(pHead2); if(num==s.size()) return pHead2; else{ pHead2=pHead2->next; num++; } } return pHead2; } };