diff --git a/src/data-structures/doubly-linked-list/DoublyLinkedList.js b/src/data-structures/doubly-linked-list/DoublyLinkedList.js index e66e016d..5bfea777 100644 --- a/src/data-structures/doubly-linked-list/DoublyLinkedList.js +++ b/src/data-structures/doubly-linked-list/DoublyLinkedList.js @@ -243,9 +243,11 @@ export default class DoublyLinkedList { while (currNode) { // Store next node. nextNode = currNode.next; + prevNode = currNode.previous; // Change next node of the current node so it would link to previous node. currNode.next = prevNode; + currNode.previous = nextNode; // Move prevNode and currNode nodes one step forward. prevNode = currNode; diff --git a/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js b/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js index ca6be64f..68bd1c44 100644 --- a/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js +++ b/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js @@ -236,22 +236,43 @@ describe('DoublyLinkedList', () => { linkedList .append(1) .append(2) - .append(3); + .append(3) + .append(4); - expect(linkedList.toString()).toBe('1,2,3'); + expect(linkedList.toString()).toBe('1,2,3,4'); expect(linkedList.head.value).toBe(1); - expect(linkedList.tail.value).toBe(3); + expect(linkedList.tail.value).toBe(4); // Reverse linked list. linkedList.reverse(); - expect(linkedList.toString()).toBe('3,2,1'); - expect(linkedList.head.value).toBe(3); + expect(linkedList.toString()).toBe('4,3,2,1'); + + expect(linkedList.head.previous).toBeNull(); + expect(linkedList.head.value).toBe(4); + expect(linkedList.head.next.value).toBe(3); + expect(linkedList.head.next.next.value).toBe(2); + expect(linkedList.head.next.next.next.value).toBe(1); + + expect(linkedList.tail.next).toBeNull(); expect(linkedList.tail.value).toBe(1); + expect(linkedList.tail.previous.value).toBe(2); + expect(linkedList.tail.previous.previous.value).toBe(3); + expect(linkedList.tail.previous.previous.previous.value).toBe(4); // Reverse linked list back to initial state. linkedList.reverse(); - expect(linkedList.toString()).toBe('1,2,3'); + expect(linkedList.toString()).toBe('1,2,3,4'); + + expect(linkedList.head.previous).toBeNull(); expect(linkedList.head.value).toBe(1); - expect(linkedList.tail.value).toBe(3); + expect(linkedList.head.next.value).toBe(2); + expect(linkedList.head.next.next.value).toBe(3); + expect(linkedList.head.next.next.next.value).toBe(4); + + expect(linkedList.tail.next).toBeNull(); + expect(linkedList.tail.value).toBe(4); + expect(linkedList.tail.previous.value).toBe(3); + expect(linkedList.tail.previous.previous.value).toBe(2); + expect(linkedList.tail.previous.previous.previous.value).toBe(1); }); });