-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedListFindLoop.js
More file actions
92 lines (79 loc) · 1.53 KB
/
linkedListFindLoop.js
File metadata and controls
92 lines (79 loc) · 1.53 KB
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
class Node {
constructor (value) {
this._next = null
this._value = value
}
set value (value) {
this._value = value
}
get value () {
return this._value
}
set next (node) {
this._next = node
}
get next () {
return this._next
}
}
class LinkedList {
constructor () {
this._head = null
this._tail = null
this._size = 0
}
get head () {
return this._head
}
add (data) {
const node = new Node(data)
if (this._size === 0) {
this._head = node
this._tail = node
} else {
this._tail.next = node
this._tail = node
}
this._size++
}
makeLoop () {
this._tail.next = this._head
return this
}
}
const sampleList = new LinkedList()
sampleList.add(1)
sampleList.add(2)
sampleList.add(3)
sampleList.add(4)
sampleList.add(5)
sampleList.add(6)
sampleList.add(7)
sampleList.add(8)
sampleList.add(9)
sampleList.add(10)
const toArray = (linkedList) => {
const result = []
let currentNode = linkedList.head
while (currentNode) {
result.push(currentNode.value)
currentNode = currentNode.next
}
return result
}
// O(n) time / O(1) space
const hasLoop = (linkedList) => {
let tortoise = linkedList.head
let hare = linkedList.head
while (hare.next != null && tortoise && tortoise.next != null) {
hare = hare.next
tortoise = tortoise.next.next
if (hare === tortoise) {
return true
}
}
return false
}
console.log(toArray(sampleList))
console.log(hasLoop(sampleList))
console.log(hasLoop(sampleList.makeLoop()))