-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
70 lines (67 loc) · 1.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
*
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
let headA_p = headA;
let headB_p = headB;
while (headA_p !== headB_p) {
headA_p = headA_p ? headA_p.next : headA;
headB_p = headB_p ? headB_p.next : headB;
}
return headA_p;
};
/**
*
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
let headA_length = 0;
let headB_length = 0;
let headA_p = headA;
let headB_p = headB;
while (headA_p) {
headA_length ++;
headA_p = headA_p.next;
}
while (headB_p) {
headB_length ++;
headB_p = headB_p.next;
}
headA_p = headA;
headB_p = headB;
if (headA_length > headB_length) {
while (headA_length - headB_length > 0) {
headA_length --;
headA_p = headA_p.next;
}
}
if (headB_length > headA_length) {
while (headB_length - headA_length > 0) {
headB_length --;
headB_p = headB_p.next;
}
}
while (headA_p !== headB_p) {
headA_p = headA_p.next;
headB_p = headB_p.next;
}
return headB_p;
};
module.exports = {
id:'160',
title:'Intersection of Two Linked Lists',
url:'https://leetcode.com/problems/intersection-of-two-linked-lists/',
difficulty:'easy',
};