思路将两个链表组合起来,这样长度就相等了,然后双指针遍历,O(m+n) O(1)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA == nullptr ? headB : pA->next;
pB = pB == nullptr ? headA : pB->next;
}
return pA;
}
};
哈希
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*>myset;
ListNode*left=headA;
ListNode*right=headB;
while(left!=nullptr){
myset.insert(left);
left=left->next;
}
while(right!=nullptr){
if(myset.count(right))
return right;
right=right->next;
}
return nullptr;
}
};