题目描述:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
相交链表的定义:2个链表如果相交,则自相交节点开始,后续节点均相交
思路:
1、双指针法
itrA = headA;
itrB = headB;
hasReachedTailForA -> false;
hasReachedTailForB -> false;
while (itrA != nullptr || itrB != nullptr) {
if (itrA == itrB) {
return itrA;
}
if (itrA->next == nullptr && not hasReachedTailForA) {
itrA = headB;
hasReachedTailForA = true;
} else {
itrA = itrA->next;
}
if (itrB->next == nullptr && not hasReachedTailForB) {
itrB = headA;
hasReachedTailForB = true;
} else {
itrB = itrB->next;
}
}
return nullptr;
2、HashTable
while (itrA != nullptr) {
hasTable[itrA] = itrA->val;
itrA = itrA->next;
}
while (itrB != nullptr) {
if (hasTable.find(itrB) != hasTable.end()) {
return itrB;
}
itrB = itrB->next;
}
return nullptr;