Leetcode题解之 —— 相交链表

思路


缓存方式

题解


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
const cache = new Map();
let [currentNodeA, currentNodeB] = [headA, headB];

while (currentNodeA) {
cache.set(currentNodeA, currentNodeA);
currentNodeA = currentNodeA.next;
}

while (currentNodeB) {
if (cache.has(currentNodeB)) {
return currentNodeB;
}
currentNodeB = currentNodeB.next;
}

return null;
};