Skip to content
Permalink
Newer
Older
100644 76 lines (65 sloc) 1.74 KB
1
/**
2
*
3
* How to find the node at which the intersection of two singly linked lists begins.
4
*
5
* Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect.
6
* If the two linked lists have no intersection at all, return null.
7
*
8
*/
9
10
class Node{
11
constructor(value, next = null){
12
this.value = value
13
this.next = next
14
}
15
}
16
17
// function getIntersectionNode(headA, headB){
18
// if(headA === null || headB === null){
19
// return null
20
// }
21
// let listA = headA
22
// let listB = headB
24
// while(listA !== null){
25
// listA.visited = true
26
// listA = listA.next
27
// }
28
29
// while(listB !== null){
30
// if(listB.visited === true){
31
// return listB
32
// }
33
// listB = listB.next
34
// }
35
36
// return null
37
// }
38
39
function getIntersectionNode (headA, headB){
40
if(headA === null || headB === null){
41
return null
42
}
43
let listA = headA
44
let listB = headB
45
47
listA = listA.next
48
listB = listB.next
49
50
if(listA === listB){
51
return listA
52
}
53
if(listA === null){
54
listA = headB
55
}
56
if(listB === null){
57
listB = headA
58
}
61
}
62
63
let list1 = new Node(4)
64
list1.next = new Node(1)
65
list1.next.next = new Node(8)
66
list1.next.next.next = new Node(4)
67
list1.next.next.next.next = new Node(5)
68
69
let list2 = new Node(5)
70
list2.next = new Node(6)
71
list2.next.next = list1.next
72
list2.next.next.next = list1.next.next
73
list2.next.next.next.next = list1.next.next.next
74
list2.next.next.next.next.next = list1.next.next.next.next
75
76
console.log('Intersection Node of two linkedlist', getIntersectionNode(list1, list2))