/
solution.ts
60 lines (53 loc) · 1.5 KB
/
solution.ts
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
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Hash_Table #Two_Pointers #Linked_List
// #Data_Structure_II_Day_11_Linked_List #Udemy_Linked_List #Big_O_Time_O(M+N)_Space_O(1)
// #2023_10_08_Time_67_ms_(93.58%)_Space_50.8_MB_(40.54%)
import { ListNode } from '../../com_github_leetcode/listnode'
/*
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function getNode(index: number, startNode: ListNode): ListNode {
let node = startNode
while (index > 0) {
node = node.next
--index
}
return node
}
function getListSize(node: ListNode): number {
let size = 0
while (node) {
++size
node = node.next
}
return size
}
function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
const sizeA = getListSize(headA)
const sizeB = getListSize(headB)
let startA = headA
let startB = headB
let diff = Math.abs(sizeA - sizeB)
if (sizeB > sizeA) {
startB = getNode(diff, startB)
}
if (sizeA > sizeB) {
startA = getNode(diff, startA)
}
while (startB && startA) {
if (startA === startB) {
return startA
}
startA = startA.next
startB = startB.next
}
return null
}
export { getIntersectionNode }