forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSingleCircularLinkedList.js.js
97 lines (77 loc) · 1.55 KB
/
SingleCircularLinkedList.js.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
class Node {
constructor (data, next = null) {
this.data = data
this.next = next
}
}
class SinglyCircularLinkedList {
constructor () {
this.head = null
this.size = 0
}
insert (data) {
const node = new Node(data)
if (!this.head) {
node.next = node
this.head = node
this.size++
} else {
node.next = this.head
let current = this.head
while (current.next.data !== this.head.data) {
current = current.next
}
current.next = node
this.size++
}
}
insertAt (index, data) {
const node = new Node(data)
if (index < 0 || index > this.size) return
if (index === 0) {
this.head = node
this.size = 1
return
}
let previous
let count = 0
let current = this.head
while (count < index) {
previous = current
current = current.next
count++
}
node.next = current
previous.next = node
this.size++
}
remove () {
if (!this.head) return
let prev
let current = this.head
while (current.next !== this.head) {
prev = current
current = current.next
}
prev.next = this.head
this.size--
}
printData () {
let count = 0
let current = this.head
while (current !== null && count !== this.size) {
console.log(current.data + '\n')
current = current.next
count++
}
}
}
const ll = new SinglyCircularLinkedList()
ll.insert(10)
ll.insert(20)
ll.insert(30)
ll.insert(40)
ll.insert(50)
ll.insertAt(5, 60)
ll.remove(5)
ll.printData()