File tree Expand file tree Collapse file tree 1 file changed +95
-0
lines changed Expand file tree Collapse file tree 1 file changed +95
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=160 lang=javascript
3
+ *
4
+ * [160] 相交链表
5
+ *
6
+ * 有两种办法
7
+ * 1. 用 Set 存 A 中存在的节点, 然后遍历 B 查找是否有重合
8
+ * 2. 计算 A 和 B 的长度, 把较长的部分去掉使其等长, 然后 A 和 B 一起向下遍历
9
+ * 因为 A 和 B 是等长的, 那么如果有相交则一定是当前遍历到的 a 和 b 节点相等
10
+ * 如果找不到相等的节点, 那就是不想交
11
+ */
12
+
13
+ // @lc code=start
14
+ /**
15
+ * Definition for singly-linked list.
16
+ * function ListNode(val) {
17
+ * this.val = val;
18
+ * this.next = null;
19
+ * }
20
+ */
21
+
22
+ /**
23
+ * @param {ListNode } headA
24
+ * @param {ListNode } headB
25
+ * @return {ListNode }
26
+ */
27
+ /**
28
+ * Definition for singly-linked list.
29
+ * function ListNode(val) {
30
+ * this.val = val;
31
+ * this.next = null;
32
+ * }
33
+ */
34
+
35
+ /**
36
+ * @param {ListNode } headA
37
+ * @param {ListNode } headB
38
+ * @return {ListNode }
39
+ */
40
+ var getIntersectionNode = function ( headA , headB ) {
41
+ function getLen ( head ) {
42
+ let c = 0 ;
43
+ while ( head ) {
44
+ c ++ ;
45
+ head = head . next ;
46
+ }
47
+ return c ;
48
+ }
49
+ const lenA = getLen ( headA ) ;
50
+ const lenB = getLen ( headB ) ;
51
+ if ( lenA > lenB ) {
52
+ let n = lenA - lenB ;
53
+ while ( n > 0 ) {
54
+ n -- ;
55
+ headA = headA . next ;
56
+ }
57
+ } else {
58
+ let n = lenB - lenA ;
59
+ while ( n > 0 ) {
60
+ n -- ;
61
+ headB = headB . next ;
62
+ }
63
+ }
64
+
65
+ let curA = headA , curB = headB ;
66
+ while ( curA && curB ) {
67
+ if ( curA === curB ) {
68
+ return curA ;
69
+ }
70
+ curA = curA . next ;
71
+ curB = curB . next ;
72
+ }
73
+ return null ;
74
+ } ;
75
+
76
+ // var getIntersectionNode = function(headA, headB) {
77
+ // const set = new Set();
78
+ // let a = headA;
79
+ // while (a) {
80
+ // set.add(a);
81
+ // a = a.next;
82
+ // }
83
+
84
+ // let b = headB;
85
+ // while (b) {
86
+ // if (set.has(b)) {
87
+ // return b;
88
+ // }
89
+ // b = b.next;
90
+ // }
91
+
92
+ // return null;
93
+ // };
94
+ // @lc code=end
95
+
You can’t perform that action at this time.
0 commit comments