forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path160-IntersectionofTwoLinkedLists.js
110 lines (91 loc) · 2.12 KB
/
160-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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* because there is an intersection btw two linkedlists, first align the head of longer list with
* the shorter one's head. Then just keep moving the heads of both linkedlists
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
var lenA = getLength(headA);
var lenB = getLength(headB);
while(lenA < lenB) {
headB = headB.next;
lenB--;
}
while(lenB < lenA) {
headA = headA.next;
lenA--;
}
while(headA !== headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
};
var getLength = function(listHead) {
var length = 0;
while (listHead) {
length++;
listHead = listHead.next;
}
return length;
};
// 2nd try without knowing the length
var getIntersectionNode = function(headA, headB) {
var intersection = null;
var pa = headA;
var pb = headB;
if (!pa || !pb) {
return intersection;
}
while (pa || pb) {
if (pa && pb && pa.val === pb.val) {
intersection = pa;
}
// this can be replace by pa === pb
while (pa && pb && pa.val === pb.val) {
pa = pa.next;
pb = pb.next;
}
if (pa === null && pb === null) {
break;
} else if (pa === null) {
pa = headB;
} else if (pb === null) {
pb = headA;
} else {
pa = pa.next;
pb = pb.next;
}
}
return intersection;
};
// more concise version, compared to version 2
var getIntersectionNode = function(headA, headB) {
var pa = headA;
var pb = headB;
if (!pa || !pb) {
return null;
}
while (pa && pb && pa !== pb) {
pa = pa.next;
pb = pb.next;
if (pa === pb) {
return pa;
}
if (!pa) {
pa = headB;
}
if (!pb) {
pb = headA;
}
}
return pa;
};