Skip to content

Commit 20db10b

Browse files
committed
--update: addAt()
1 parent dcafcb7 commit 20db10b

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/_DataStructures_/LinkedList/LinkedList.test.js

+28-1
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ describe('Data Structures: Linked Lists', () => {
175175
list.addAtEnd('There!');
176176
list.addAtEnd('Welcome');
177177
});
178-
178+
179179
it('Should return `null` for empty list regardless of index value', () => {
180180
list.delete();
181181
expect(list.getAt(10)).toEqual(null);
@@ -189,5 +189,32 @@ describe('Data Structures: Linked Lists', () => {
189189
expect(list.getAt(10).data).toEqual('Welcome');
190190
});
191191
});
192+
193+
describe('addAt(index, value)', () => {
194+
beforeEach(() => {
195+
list.addAtBeginning('Hello');
196+
list.addAtEnd('There!');
197+
list.addAtEnd('Welcome');
198+
});
199+
200+
it('Should add at the beginning of empty list', () => {
201+
list.delete();
202+
list.addAt(10, 'Boom');
203+
expect(list.getFirst().data).toEqual('Boom');
204+
});
205+
206+
it('Should add at the end of the list if the index is out of bound', () => {
207+
list.addAtEnd(1010);
208+
list.addAt(10, 'Boom');
209+
expect(list.getLast().data).toEqual('Boom');
210+
});
211+
212+
it('Should add new element at the given position', () => {
213+
list.addAt(2, 'Stranger');
214+
expect(list.getAt(2).data).toEqual('Stranger');
215+
expect(list.getAt(1).data).toEqual('There!');
216+
expect(list.getAt(0).data).toEqual('Hello');
217+
});
218+
});
192219
});
193220
});

src/_DataStructures_/LinkedList/index.js

+23
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,29 @@ class LinkedList {
8484
return address;
8585
}
8686

87+
addAt(index, element) {
88+
if (!this.head) {
89+
return this.addAtBeginning(element);
90+
}
91+
92+
if (index >= this.length()) {
93+
return this.addAtEnd(element);
94+
}
95+
96+
let address = this.head;
97+
let previous = this.head;
98+
let count = index;
99+
100+
while (count) {
101+
previous = address;
102+
address = address.next;
103+
count -= 1;
104+
}
105+
106+
previous.next = new Node(element, previous.next);
107+
return 0;
108+
}
109+
87110
length() {
88111
let address = this.head;
89112
let count = 0;

0 commit comments

Comments
 (0)