Skip to content

Commit bf94b22

Browse files
committed
--update: addAtEnd()
1 parent 024eebb commit bf94b22

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/_DataStructures_/LinkedList/LinkedList.test.js

+9
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,15 @@ describe('Data Structures: Linked Lists', () => {
4040
expect(list.head.data).toEqual(15);
4141
});
4242

43+
it('Should add element at end using list.addAtEnd()', () => {
44+
list.addAtEnd(12);
45+
expect(list.head.data).toEqual(12);
46+
47+
list.addAtEnd(15);
48+
expect(list.head.data).toEqual(12);
49+
expect(list.head.next.data).toEqual(15);
50+
});
51+
4352
it('Should return the present size of the list using list.length()', () => {
4453
expect(list.length()).toEqual(0);
4554
list.addAtBeginning(1);

src/_DataStructures_/LinkedList/index.js

+16
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,22 @@ class LinkedList {
2121
}
2222
}
2323

24+
addAtEnd(element) {
25+
const node = new Node(element, null);
26+
27+
if (!this.head) {
28+
this.head = node;
29+
} else {
30+
let address = this.head;
31+
32+
while (address.next) {
33+
address = address.next;
34+
}
35+
36+
address.next = node;
37+
}
38+
}
39+
2440
length() {
2541
let address = this.head;
2642
let count = 0;

0 commit comments

Comments
 (0)