diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index 3d2ccb46..2622fdfa 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -28,7 +28,35 @@ export default class LinkedList { } prepend(value) { + const newNode = new Node(value); this.head = new Node(value, this.head); + + return newNode; + } + + delete(value) { + if (!this.head) { + return null; + } + + let deletedNode = null; + + if (this.head.value === value) { + deletedNode = this.head; + this.head = this.head.next; + } + + let currentNode = this.head; + + while (currentNode.next) { + if (currentNode.next.value === value) { + deletedNode = currentNode.next; + currentNode.next = currentNode.next.next; + } + currentNode = currentNode.next; + } + + return deletedNode; } toArray() { diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index 37a1ce4c..0731ca5f 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -3,21 +3,51 @@ import LinkedList from '../LinkedList'; describe('LinkedList', () => { it('should create empty linked list', () => { const linkedList = new LinkedList(); - expect(linkedList).toBeDefined(); + expect(linkedList.toString()).toBe(''); }); it('should append node to linked list', () => { const linkedList = new LinkedList(); - linkedList.append(1); - linkedList.append(2); + + const node1 = linkedList.append(1); + const node2 = linkedList.append(2); + + expect(node1.value).toBe(1); + expect(node2.value).toBe(2); + expect(linkedList.toString()).toBe('1,2'); }); it('should prepend node to linked list', () => { const linkedList = new LinkedList(); + + const node1 = linkedList.append(1); + const node2 = linkedList.prepend(2); + + expect(node1.value).toBe(1); + expect(node2.value).toBe(2); + + expect(linkedList.toString()).toBe('2,1'); + }); + + it('should delete node by value from linked list', () => { + const linkedList = new LinkedList(); + linkedList.append(1); linkedList.append(2); - linkedList.prepend(3); - expect(linkedList.toString()).toBe('3,1,2'); + linkedList.append(3); + linkedList.append(3); + linkedList.append(4); + linkedList.append(5); + + const deletedNode = linkedList.delete(3); + expect(deletedNode.value).toBe(3); + expect(linkedList.toString()).toBe('1,2,3,4,5'); + + linkedList.delete(3); + expect(linkedList.toString()).toBe('1,2,4,5'); + + linkedList.delete(1); + expect(linkedList.toString()).toBe('2,4,5'); }); });