/**
* 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) {
while (headA && headB) {
if (headA->val != headB->val) headB = headB->next;
else return headA;
if (headB && headB->val != headA->val) headA = headA->next;
else return headA;
}
return nullptr;
}
};
//Above is the first method with zero memory needed!
//Below is the second method, I do not why the first method cannot pass all the cases! but the second method can.
/**
* 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*> Set;
while (headA) {
Set.insert(headA);
headA = headA->next;
}
while (headB) {
if (Set.find(headB) != Set.end()) return headB;
headB = headB->next;
}
return nullptr;
}
};