Skip to content

Commit 14baa6d

Browse files
committed
feat: 160. 相交链表
1 parent 8b77b84 commit 14baa6d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// LeetCode 原题:https://leetcode.cn/problems/intersection-of-two-linked-lists/
2+
3+
/**
4+
* Definition for singly-linked list.
5+
* function ListNode(val) {
6+
* this.val = val;
7+
* this.next = null;
8+
* }
9+
*/
10+
11+
/**
12+
* 假设「第一个公共节点」为 node ,「链表 headA」的节点数量为 a ,「链表 headB」的节点数量为 b ,「两链表的公共尾部」的节点数量为 c ,则有:
13+
* 头节点 headA 到 node 中间共有 a-c 个节点
14+
* 头节点 headB 到 node 中间共有 b-c 个节点
15+
* 那么我们分别使用指针 pA 和 pB 遍历链表 headA 和 headB
16+
* 当 pA 指针走完 headA 的时,让 pA 指向 headB 头节点继续往后遍历
17+
* 同样,当 pB 指针走完 headB 的时,让 pB 指向 headA 头节点继续往后遍历
18+
* 那么会有这种情况:
19+
* 当 pA 和 pB 都走到 node 节点时,pA 和 pB 走过的节点数是相等的
20+
* 即:a+(b-c) = b+(a-c)
21+
* 那么如果 node 存在,则 pA 就会等于 pB,也就是他们都指向 node
22+
* 如果不存在 node,则 pA 和 pB 最后指向的都是 null
23+
* @param {ListNode} headA
24+
* @param {ListNode} headB
25+
* @return {ListNode}
26+
*/
27+
var getIntersectionNode = function (headA, headB) {
28+
let pA = headA;
29+
let pB = headB;
30+
31+
while (pA !== pB) {
32+
pA = pA ? pA.next : headB;
33+
pB = pB ? pB.next : headA;
34+
}
35+
36+
return pA;
37+
};

0 commit comments

Comments
 (0)