1 拼接两个链表再乘2,使得加长两两链表路径长相同—空间复杂度 O ( 1 ) O(1) O(1)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB) return nullptr;
auto nodea = headA;
auto nodeb = headB;
// 当两指针相遇时返回其中一个指针即可
while (nodea != nodeb) {
nodea = nodea ? nodea->next : headB; // 若遍历headA的指针到尾部,则转去遍历headB链表,若两链表不相交,则最后两指针均为nullptr
nodeb = nodeb ? nodeb->next : headA;
}
return nodea;
}
};
2 哈希集合—空间复杂度 O ( m + n ) O(m+n) O(m+n)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB) return nullptr;
set<ListNode*> s;
auto nodea = headA;
auto nodeb = headB;
while (nodea || nodeb) {
if (nodea) {
if (s.count(nodea)) return nodea;
else s.insert(nodea);
nodea = nodea->next;
}
if (nodeb) {
if (s.count(nodeb)) return nodeb;
else s.insert(nodeb);
nodeb = nodeb->next;
}
}
return nullptr;
}
};