Add more test cases for linked list reversion.

This commit is contained in:
Oleksii Trekhleb 2018-09-08 12:16:15 +03:00
parent 4989a6a3b0
commit 2feec48ea6
2 changed files with 17 additions and 8 deletions

View File

@ -243,8 +243,8 @@ export default class LinkedList {
} }
/** /**
* Reverse a singly linked list use to three variables * Reverse a linked list.
* @returns {ReservedLinkedList} * @returns {LinkedList}
*/ */
reverse() { reverse() {
let currNode = this.head; let currNode = this.head;
@ -252,18 +252,18 @@ export default class LinkedList {
let nextNode = null; let nextNode = null;
while (currNode) { while (currNode) {
// Store next node // Store next node.
nextNode = currNode.next; 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; currNode.next = prevNode;
// Move forward prev and current nodes one step // Move prevNode and currNode nodes one step forward.
prevNode = currNode; prevNode = currNode;
currNode = nextNode; currNode = nextNode;
} }
// Reset head, tail // Reset head and tail.
this.tail = this.head; this.tail = this.head;
this.head = prevNode; this.head = prevNode;

View File

@ -243,15 +243,24 @@ describe('LinkedList', () => {
expect(() => linkedList.reverseTraversal(linkedList.head)).toThrow(); expect(() => linkedList.reverseTraversal(linkedList.head)).toThrow();
}); });
it('should reverse the singly linked list', () => { it('should reverse linked list', () => {
const linkedList = new LinkedList(); const linkedList = new LinkedList();
// Add test values to linked list.
linkedList linkedList
.append(1) .append(1)
.append(2) .append(2)
.append(3); .append(3);
expect(linkedList.toString()).toBe('1,2,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);
}); });
}); });