Skip to content

Commit 63ac632

Browse files
committed
update: size property aded
1 parent a3d841e commit 63ac632

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

src/_DataStructures_/LinkedList/index.js

+13-11
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,22 @@ class Node {
22
constructor(data, next) {
33
this.data = data;
44
this.next = next;
5-
this.length = 0;
65
}
76
}
87

98
class LinkedList {
109
constructor() {
1110
this.head = null;
1211
this.tail = null;
12+
this.size = 0;
1313
}
1414

1515
addAtBeginning(element) {
1616
this.head = new Node(element, this.head);
1717
if (!this.tail) {
1818
this.tail = this.head;
1919
}
20+
this.size += 1;
2021
return this.head;
2122
}
2223

@@ -27,19 +28,20 @@ class LinkedList {
2728
const node = new Node(element, null);
2829
this.tail.next = node;
2930
this.tail = node;
31+
this.size += 1;
3032
return node;
3133
}
3234

3335
removeFromBeginning() {
3436
if (!this.head) {
35-
this.tail = null;
3637
return null;
3738
}
3839
if (this.head.next === null) {
3940
this.tail = this.head;
4041
}
4142
const node = this.head;
4243
this.head = this.head.next;
44+
this.size -= 1;
4345
return node;
4446
}
4547

@@ -57,6 +59,7 @@ class LinkedList {
5759

5860
const node = this.tail.next;
5961
this.tail.next = null;
62+
this.size -= 1;
6063
return node;
6164
}
6265

@@ -108,8 +111,10 @@ class LinkedList {
108111
count -= 1;
109112
}
110113

111-
previous.next = new Node(element, previous.next);
112-
return null;
114+
const node = new Node(element, previous.next);
115+
previous.next = node;
116+
this.size += 1;
117+
return node;
113118
}
114119

115120
removeAt(index) {
@@ -133,21 +138,18 @@ class LinkedList {
133138

134139
const node = address;
135140
previous.next = address.next.next;
141+
this.size -= 1;
136142
return node;
137143
}
138144

139145
length() {
140-
let address = this.head;
141-
let count = 0;
142-
while (address) {
143-
count += 1;
144-
address = address.next;
145-
}
146-
return count;
146+
return this.size;
147147
}
148148

149149
delete() {
150150
this.head = null;
151+
this.tail = this.head;
152+
this.size = 0;
151153
}
152154
}
153155

0 commit comments

Comments
 (0)