Skip to content

Commit dcafcb7

Browse files
committedJan 4, 2019
--update: getAt(index)
1 parent fd0cb50 commit dcafcb7

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed
 

‎src/_DataStructures_/LinkedList/LinkedList.test.js

+21
Original file line numberDiff line numberDiff line change
@@ -168,5 +168,26 @@ describe('Data Structures: Linked Lists', () => {
168168
expect(list.getFirst().data).toEqual(15);
169169
});
170170
});
171+
172+
describe('getAt(index)', () => {
173+
beforeEach(() => {
174+
list.addAtBeginning('Hello');
175+
list.addAtEnd('There!');
176+
list.addAtEnd('Welcome');
177+
});
178+
179+
it('Should return `null` for empty list regardless of index value', () => {
180+
list.delete();
181+
expect(list.getAt(10)).toEqual(null);
182+
});
183+
184+
it('Should return the node for given index', () => {
185+
expect(list.getAt(1).data).toEqual('There!');
186+
});
187+
188+
it('Should return the last element for large index', () => {
189+
expect(list.getAt(10).data).toEqual('Welcome');
190+
});
191+
});
171192
});
172193
});

‎src/_DataStructures_/LinkedList/index.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,9 @@ class LinkedList {
2121
this.head = node;
2222
} else {
2323
let address = this.head;
24-
2524
while (address.next) {
2625
address = address.next;
2726
}
28-
2927
address.next = node;
3028
}
3129
}
@@ -71,6 +69,21 @@ class LinkedList {
7169
return address;
7270
}
7371

72+
getAt(index) {
73+
if (!this.length()) {
74+
return null;
75+
}
76+
let address = this.head;
77+
let count = index;
78+
79+
while (count && address.next) {
80+
address = address.next;
81+
count -= 1;
82+
}
83+
84+
return address;
85+
}
86+
7487
length() {
7588
let address = this.head;
7689
let count = 0;

0 commit comments

Comments
 (0)
Please sign in to comment.