Skip to content

Commit 9ee032b

Browse files
committed
--update: find element from last of the linked list
1 parent 39bd5bb commit 9ee032b

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const { getElementFromlast } = require('.');
2+
const { LinkedList } = require('../index');
3+
4+
describe('Find the middle node of a LinkedList', () => {
5+
let list = null;
6+
beforeEach(() => {
7+
list = new LinkedList();
8+
list.addAtBeginning('Hello');
9+
list.addAtEnd('World!');
10+
list.addAtEnd('Welcome');
11+
list.addAtEnd('to');
12+
list.addAtEnd('the');
13+
list.addAtEnd('world');
14+
list.addAtEnd('of');
15+
list.addAtEnd('JavaScript');
16+
});
17+
18+
it('Should return `null` for empty list', () => {
19+
list.delete();
20+
expect(getElementFromlast(list, 10)).toEqual(null);
21+
});
22+
23+
it('Should return `world` as 3rd from last of the list', () => {
24+
expect(getElementFromlast(list, 3).data).toEqual('world');
25+
});
26+
27+
it('Should return `Welcome` as 6th from last of the list', () => {
28+
expect(getElementFromlast(list, 6).data).toEqual('Welcome');
29+
});
30+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function getElementFromlast(linkedList, index) {
2+
let normal = linkedList.getFirst();
3+
let nth = linkedList.getFirst();
4+
let count = 0;
5+
6+
if (!normal) {
7+
return null;
8+
}
9+
10+
while (normal) {
11+
if (count >= index) {
12+
nth = nth.next;
13+
}
14+
normal = normal.next;
15+
count += 1;
16+
}
17+
return nth;
18+
}
19+
20+
module.exports = {
21+
getElementFromlast,
22+
};

0 commit comments

Comments
 (0)