题目描述
法一)哈希表
class Solution{
public:
ListNode* getIntersectionNode (ListNode* headA, ListNode* headB){
unordered_set<ListNode*> st;
ListNode* temp = headA;
while(temp){
st.insert(temp);
temp = temp->next;
}
temp = headB;
while(temp){
if(st.count(temp)){
return temp;
}
temp = temp->next;
}
return NULL;
}
};
法二)双指针
ListNode* getIntersectionNode (ListNode* headA, ListNode* headB){
if(headA == NULL || headB==NULL){
return NULL;
}
ListNode* pa, pb = headA, headB;
while(pa!=pb){
pa = pa==NULL ? headB : pa->next;
pb = pb==NULL ? headA : pb->next;
}
return pa;
}