思路一:双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == nullptr or headB == nullptr){
return nullptr;
}
ListNode* pa = headA;
ListNode* pb = headB;
while(pa != pb){//当指针不相等
pa = pa == nullptr ? headB : pa->next;//指针 A 先遍历完链表 headA ,再开始遍历链表 headB ,当走到 node 时a+(b−c)
pb = pb == nullptr ? headA : pb->next;//指针 B 先遍历完链表 headB ,再开始遍历链表 headA ,当走到 node 时,共走步数为:b + (a - c)
}
return pa;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*>s;
ListNode* temp;
temp = headA;
while(temp){
s.insert(temp);
temp = temp->next;
}
temp = headB;
while(temp){
if(s.count(temp)){
return temp;
}
temp = temp->next;
}
return nullptr;
}
};