用集合,先把A链表存进集合,然后遍历B链表,每次判断节点是否在集合里,在的话就是第一个相交,用集合来判断链表公共元素问题太方便了
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*> s;
while(headA){
s.insert(headA);
headA = headA->next;
}
while(headB){
if(s.count(headB)){
return headB;
}
headB = headB->next;
}
return NULL;
}
};
双指针数学构思,拼接,AB,BA,
View Code
1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 if (headA == nullptr || headB == nullptr) { 5 return nullptr; 6 } 7 ListNode *pA = headA, *pB = headB; 8 while (pA != pB) { 9 pA = pA == nullptr ? headB : pA->next; 10 pB = pB == nullptr ? headA : pB->next; 11 } 12 return pA; 13 } 14 }; 15 16 作者:LeetCode-Solution 17 链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode-solutio-a8jn/ 18 来源:力扣(LeetCode) 19 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。