Skip to content

Commit 2c93a3d

Browse files
committed
https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
1 parent fcdeefe commit 2c93a3d

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
3+
* Definition for singly-linked list.
4+
* function ListNode(val) {
5+
* this.val = val;
6+
* this.next = null;
7+
* }
8+
*/
9+
10+
/**
11+
* @param {ListNode} headA
12+
* @param {ListNode} headB
13+
* @return {ListNode}
14+
*/
15+
var getIntersectionNode = function(headA, headB) {
16+
let curA = headA,
17+
curB = headB,
18+
lenA = 0,
19+
lenB = 0;
20+
// 求两个链表的长度
21+
while (curA) {
22+
lenA++;
23+
curA = curA.next;
24+
}
25+
while (curB) {
26+
lenB++;
27+
curB = curB.next;
28+
}
29+
// 把两个链表的位置从后往前对齐
30+
let toBeStart = Math.abs(lenA - lenB);
31+
curA = headA;
32+
curB = headB;
33+
if (lenA > lenB) {
34+
while (toBeStart > 0) {
35+
curA = curA.next;
36+
toBeStart--;
37+
}
38+
} else {
39+
while (toBeStart > 0) {
40+
curB = curB.next;
41+
toBeStart--;
42+
}
43+
}
44+
// 至此两个链表从后往前对齐了
45+
while (curA && curB) {
46+
if (curA == curB) return curA;
47+
curA = curA.next;
48+
curB = curB.next;
49+
}
50+
return null;
51+
};

linked-list/sum-lists-lcci-submissions.js linked-list/sum-lists-lcci.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* https://leetcode-cn.com/problems/sum-lists-lcci/submissions/
2+
* https://leetcode-cn.com/problems/sum-lists-lcci
33
* Definition for singly-linked list.
44
* function ListNode(val) {
55
* this.val = val;

0 commit comments

Comments
 (0)