-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathcircular-linked-list2.js
More file actions
119 lines (93 loc) · 2.44 KB
/
circular-linked-list2.js
File metadata and controls
119 lines (93 loc) · 2.44 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class CircularLinkedList {
#size = 0;
head = null;
get size() {
return this.#size;
}
createElement(value) {
return {value, next: null, prev: null}
}
push(item) {
const element = this.createElement(item);
if(this.head === null) {
this.head = element;
this.tail = element;
} else {
this.tail.next = element;
element.prev = this.tail;
this.tail = element;
}
this.tail.next = this.head;
this.head.prev = this.tail;
this.#size += 1;
return this.size;
}
insert(item, index = 0) {
if (index < 0 || index > this.size) return;
const element = this.createElement(item);
if (index === 0) {
element.next = this.head;
if(this.head) {
this.head.prev = element;
} else {
this.tail = element;
}
this.head = element;
} else if(index === this.size) {
this.tail.next = element;
element.prev = this.tail;
this.tail = element;
} else {
let previous = this.head;
for(let i = 0; i < index - 1; i++) {
previous = previous.next;
}
element.next = previous.next;
previous.next.prev = element;
previous.next = element;
element.prev = previous;
}
this.tail.next = this.head;
this.head.prev = this.tail;
this.#size += 1;
return this.size;
}
remove(index = 0) {
if (index < 0 || index >= this.size) return null;
let removedElement = this.head;
if (index === 0) {
this.head.next.prev = null;
this.head = this.head.next;
} else if(index === this.size - 1) {
this.tail.prev.next = null;
this.tail = this.tail.prev;
} else {
let previous = this.head;
for(let i = 0; i < index - 1; i++) {
previous = previous.next;
}
removedElement = previous.next;
previous.next = removedElement.next;
removedElement.next.prev = previous;
}
if(this.head && this.tail) {
this.tail.next = this.head;
this.head.prev = this.tail;
} else {
this.head = null;
this.tail = null;
}
this.#size -= 1;
return removedElement.value;
}
toString() {
if(!this.size) return '';
let str = `${this.head.value}`;
let current = this.head.next;
while(current && current !== this.head) {
str += `, ${current.value}`;
current = current.next;
}
return str;
}
}