Add reverse() method for doubly linked list.

This commit is contained in:
Oleksii Trekhleb 2018-09-08 22:25:23 +03:00
parent 80ecbe0b3e
commit 6f27113993
2 changed files with 54 additions and 0 deletions

View File

@ -230,4 +230,32 @@ export default class DoublyLinkedList {
toString(callback) {
return this.toArray().map(node => node.toString(callback)).toString();
}
/**
* Reverse a linked list.
* @returns {DoublyLinkedList}
*/
reverse() {
let currNode = this.head;
let prevNode = null;
let nextNode = null;
while (currNode) {
// Store next node.
nextNode = currNode.next;
// Change next node of the current node so it would link to previous node.
currNode.next = prevNode;
// Move prevNode and currNode nodes one step forward.
prevNode = currNode;
currNode = nextNode;
}
// Reset head and tail.
this.tail = this.head;
this.head = prevNode;
return this;
}
}

View File

@ -228,4 +228,30 @@ describe('DoublyLinkedList', () => {
expect(node.value.customValue).toBe('test2');
expect(linkedList.find({ value: 2, customValue: 'test5' })).toBeNull();
});
it('should reverse linked list', () => {
const linkedList = new DoublyLinkedList();
// Add test values to linked list.
linkedList
.append(1)
.append(2)
.append(3);
expect(linkedList.toString()).toBe('1,2,3');
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);
// Reverse linked list back to initial state.
linkedList.reverse();
expect(linkedList.toString()).toBe('1,2,3');
expect(linkedList.head.value).toBe(1);
expect(linkedList.tail.value).toBe(3);
});
});