双指针
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*>hashset;
ListNode *hA=headA,*hB=headB;
while(hB!=hA){
hA=hA==NULL?headB:hA->next;
hB=hB==NULL?headA:hB->next;
}
return hA;
}
};
哈希表
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*>hashset;
while(headA){
hashset.insert(headA);
headA=headA->next;
}
while(headB){
if(hashset.count(headB))return headB;
headB=headB->next;
}
return NULL;
}
};