forked from codesONLY/JavaScriptONLY
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathIntersectionOfTwoLinkedLists.js
56 lines (52 loc) · 1.39 KB
/
IntersectionOfTwoLinkedLists.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
/**
* 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 shortList
let longList
let sizeA = headA
let sizeB = headB
let lengthA = 0
let lengthB = 0
while (sizeA!==null || sizeB!==null){
if(sizeA !== null) {
sizeA = sizeA.next
lengthA ++
}
if(sizeB !==null) {
sizeB = sizeB.next
lengthB ++
}
}
//starts the longest list index, to the starting point of short list
//the idea is that an intersection of a node will ALWAYS be at the end.
//therefore, SAME SIZE lists will reach the intersection value at the same time
let sizeDiff = Math.abs(lengthA - lengthB)
if(lengthB > lengthA) {
shortList = headA
longList = headB
} else {
shortList = headB
longList = headA
}
while(shortList.next !== null || longList.next !== null){
if(sizeDiff<1){
if(shortList === longList) return shortList
shortList = shortList.next
}
longList = longList.next
sizeDiff--
}
//catch any 1 length lists
if(shortList === longList) return shortList
return shortList.next
};