From 2feec48ea69eac8fb927bc6e437977979abafc91 Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Sat, 8 Sep 2018 12:16:15 +0300 Subject: [PATCH] Add more test cases for linked list reversion. --- src/data-structures/linked-list/LinkedList.js | 12 ++++++------ .../linked-list/__test__/LinkedList.test.js | 13 +++++++++++-- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index 15b54e25..d98b6284 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -243,8 +243,8 @@ export default class LinkedList { } /** - * Reverse a singly linked list use to three variables - * @returns {ReservedLinkedList} + * Reverse a linked list. + * @returns {LinkedList} */ reverse() { let currNode = this.head; @@ -252,18 +252,18 @@ export default class LinkedList { let nextNode = null; while (currNode) { - // Store next node + // Store next node. nextNode = currNode.next; - // Change next node of the current + // Change next node of the current node so it would link to previous node. currNode.next = prevNode; - // Move forward prev and current nodes one step + // Move prevNode and currNode nodes one step forward. prevNode = currNode; currNode = nextNode; } - // Reset head, tail + // Reset head and tail. this.tail = this.head; this.head = prevNode; diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index f88891cb..32290145 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -243,15 +243,24 @@ describe('LinkedList', () => { expect(() => linkedList.reverseTraversal(linkedList.head)).toThrow(); }); - it('should reverse the singly linked list', () => { + it('should reverse linked list', () => { const linkedList = new LinkedList(); + // Add test values to linked list. linkedList .append(1) .append(2) .append(3); expect(linkedList.toString()).toBe('1,2,3'); - expect(linkedList.reverse().toString()).toBe('3,2,1'); + expect(linkedList.head.value).toBe(1); + expect(linkedList.tail.value).toBe(3); + + // Reverse linked list. + linkedList.reverse(); + + expect(linkedList.toString()).toBe('3,2,1'); + expect(linkedList.head.value).toBe(3); + expect(linkedList.tail.value).toBe(1); }); });