Skip to content

Commit eac045a

Browse files
committed
feat(linkedList): remove by node
1 parent 16005f3 commit eac045a

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/data-structures/linked-lists/linked-list.js

+19
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,25 @@ class LinkedList {
265265
return false;
266266
}
267267

268+
/**
269+
* Remove element by Node
270+
* O(1)
271+
*/
272+
removeByNode(node) {
273+
if (!node) { return null; }
274+
if (node === this.first) {
275+
return this.removeFirst();
276+
}
277+
if (node === this.last) {
278+
return this.removeLast();
279+
}
280+
node.previous.next = node.next;
281+
node.next.previous = node.previous;
282+
this.size -= 1;
283+
284+
return node.value;
285+
}
286+
268287
/**
269288
* Iterate through the list yield on each node
270289
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#User-defined_iterables

src/data-structures/linked-lists/linked-list.spec.js

+27
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,33 @@ describe('LinkedList Test', () => {
223223
expect(linkedList.length).toBe(1);
224224
});
225225
});
226+
227+
describe('#removeByNode', () => {
228+
it('should remove first node', () => {
229+
const node = linkedList.first;
230+
linkedList.removeByNode(node);
231+
expect(linkedList.first.value).toEqual('found');
232+
expect(linkedList.first.previous).toEqual(null);
233+
expect(linkedList.size).toEqual(1);
234+
});
235+
236+
it('should remove last node', () => {
237+
const node = linkedList.last;
238+
linkedList.removeByNode(node);
239+
expect(linkedList.first.value).toEqual(0);
240+
expect(linkedList.first.next).toEqual(null);
241+
expect(linkedList.size).toEqual(1);
242+
});
243+
244+
it('should remove from the middle', () => {
245+
const node = linkedList.first;
246+
linkedList.addLast('last');
247+
linkedList.removeByNode(node);
248+
expect(linkedList.first.next).toEqual(linkedList.last);
249+
expect(linkedList.last.previous).toEqual(linkedList.first);
250+
expect(linkedList.size).toEqual(2);
251+
});
252+
});
226253
});
227254

228255
describe('Doubly Linked List and aliases', () => {

0 commit comments

Comments
 (0)