mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 07:01:18 +08:00
Add more test cases for linked list reversion.
This commit is contained in:
parent
4989a6a3b0
commit
2feec48ea6
@ -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;
|
||||
|
||||
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user