Skip to content

Commit 01b9a6f

Browse files
authored
Merge pull request knaxus#79 from knaxus/linked-lists
Enhancements on Linked lists
2 parents 9c4da08 + 63ac632 commit 01b9a6f

File tree

1 file changed

+31
-25
lines changed

1 file changed

+31
-25
lines changed

src/_DataStructures_/LinkedList/index.js

+31-25
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,40 @@ class Node {
88
class LinkedList {
99
constructor() {
1010
this.head = null;
11+
this.tail = null;
12+
this.size = 0;
1113
}
1214

1315
addAtBeginning(element) {
1416
this.head = new Node(element, this.head);
17+
if (!this.tail) {
18+
this.tail = this.head;
19+
}
20+
this.size += 1;
21+
return this.head;
1522
}
1623

1724
addAtEnd(element) {
18-
const node = new Node(element, null);
19-
2025
if (!this.head) {
21-
this.head = node;
22-
} else {
23-
let address = this.head;
24-
while (address.next) {
25-
address = address.next;
26-
}
27-
address.next = node;
26+
return this.addAtBeginning(element);
2827
}
28+
const node = new Node(element, null);
29+
this.tail.next = node;
30+
this.tail = node;
31+
this.size += 1;
32+
return node;
2933
}
3034

3135
removeFromBeginning() {
3236
if (!this.head) {
3337
return null;
3438
}
39+
if (this.head.next === null) {
40+
this.tail = this.head;
41+
}
3542
const node = this.head;
3643
this.head = this.head.next;
44+
this.size -= 1;
3745
return node;
3846
}
3947

@@ -47,8 +55,11 @@ class LinkedList {
4755
address = address.next;
4856
}
4957

50-
const node = address.next;
51-
address.next = null;
58+
this.tail = address;
59+
60+
const node = this.tail.next;
61+
this.tail.next = null;
62+
this.size -= 1;
5263
return node;
5364
}
5465

@@ -63,11 +74,7 @@ class LinkedList {
6374
if (!this.head) {
6475
return null;
6576
}
66-
let address = this.head;
67-
while (address.next) {
68-
address = address.next;
69-
}
70-
return address;
77+
return this.tail;
7178
}
7279

7380
getAt(index) {
@@ -104,8 +111,10 @@ class LinkedList {
104111
count -= 1;
105112
}
106113

107-
previous.next = new Node(element, previous.next);
108-
return null;
114+
const node = new Node(element, previous.next);
115+
previous.next = node;
116+
this.size += 1;
117+
return node;
109118
}
110119

111120
removeAt(index) {
@@ -129,21 +138,18 @@ class LinkedList {
129138

130139
const node = address;
131140
previous.next = address.next.next;
141+
this.size -= 1;
132142
return node;
133143
}
134144

135145
length() {
136-
let address = this.head;
137-
let count = 0;
138-
while (address) {
139-
count += 1;
140-
address = address.next;
141-
}
142-
return count;
146+
return this.size;
143147
}
144148

145149
delete() {
146150
this.head = null;
151+
this.tail = this.head;
152+
this.size = 0;
147153
}
148154
}
149155

0 commit comments

Comments
 (0)