File tree 2 files changed +52
-1
lines changed
2 files changed +52
-1
lines changed Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change 1
1
/**
2
- * https://leetcode-cn.com/problems/sum-lists-lcci/submissions/
2
+ * https://leetcode-cn.com/problems/sum-lists-lcci
3
3
* Definition for singly-linked list.
4
4
* function ListNode(val) {
5
5
* this.val = val;
You can’t perform that action at this time.
0 commit comments