mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 23:21:18 +08:00
Add reverse() method for doubly linked list.
This commit is contained in:
parent
80ecbe0b3e
commit
6f27113993
@ -230,4 +230,32 @@ export default class DoublyLinkedList {
|
|||||||
toString(callback) {
|
toString(callback) {
|
||||||
return this.toArray().map(node => node.toString(callback)).toString();
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -228,4 +228,30 @@ describe('DoublyLinkedList', () => {
|
|||||||
expect(node.value.customValue).toBe('test2');
|
expect(node.value.customValue).toBe('test2');
|
||||||
expect(linkedList.find({ value: 2, customValue: 'test5' })).toBeNull();
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user