mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
fixed doubly-linked-list reverse method omit change node's previous (#257)
This commit is contained in:
parent
4e27a979d7
commit
c18d119a6a
@ -243,9 +243,11 @@ export default class DoublyLinkedList {
|
||||
while (currNode) {
|
||||
// Store next node.
|
||||
nextNode = currNode.next;
|
||||
prevNode = currNode.previous;
|
||||
|
||||
// Change next node of the current node so it would link to previous node.
|
||||
currNode.next = prevNode;
|
||||
currNode.previous = nextNode;
|
||||
|
||||
// Move prevNode and currNode nodes one step forward.
|
||||
prevNode = currNode;
|
||||
|
@ -236,22 +236,43 @@ describe('DoublyLinkedList', () => {
|
||||
linkedList
|
||||
.append(1)
|
||||
.append(2)
|
||||
.append(3);
|
||||
.append(3)
|
||||
.append(4);
|
||||
|
||||
expect(linkedList.toString()).toBe('1,2,3');
|
||||
expect(linkedList.toString()).toBe('1,2,3,4');
|
||||
expect(linkedList.head.value).toBe(1);
|
||||
expect(linkedList.tail.value).toBe(3);
|
||||
expect(linkedList.tail.value).toBe(4);
|
||||
|
||||
// Reverse linked list.
|
||||
linkedList.reverse();
|
||||
expect(linkedList.toString()).toBe('3,2,1');
|
||||
expect(linkedList.head.value).toBe(3);
|
||||
expect(linkedList.toString()).toBe('4,3,2,1');
|
||||
|
||||
expect(linkedList.head.previous).toBeNull();
|
||||
expect(linkedList.head.value).toBe(4);
|
||||
expect(linkedList.head.next.value).toBe(3);
|
||||
expect(linkedList.head.next.next.value).toBe(2);
|
||||
expect(linkedList.head.next.next.next.value).toBe(1);
|
||||
|
||||
expect(linkedList.tail.next).toBeNull();
|
||||
expect(linkedList.tail.value).toBe(1);
|
||||
expect(linkedList.tail.previous.value).toBe(2);
|
||||
expect(linkedList.tail.previous.previous.value).toBe(3);
|
||||
expect(linkedList.tail.previous.previous.previous.value).toBe(4);
|
||||
|
||||
// Reverse linked list back to initial state.
|
||||
linkedList.reverse();
|
||||
expect(linkedList.toString()).toBe('1,2,3');
|
||||
expect(linkedList.toString()).toBe('1,2,3,4');
|
||||
|
||||
expect(linkedList.head.previous).toBeNull();
|
||||
expect(linkedList.head.value).toBe(1);
|
||||
expect(linkedList.tail.value).toBe(3);
|
||||
expect(linkedList.head.next.value).toBe(2);
|
||||
expect(linkedList.head.next.next.value).toBe(3);
|
||||
expect(linkedList.head.next.next.next.value).toBe(4);
|
||||
|
||||
expect(linkedList.tail.next).toBeNull();
|
||||
expect(linkedList.tail.value).toBe(4);
|
||||
expect(linkedList.tail.previous.value).toBe(3);
|
||||
expect(linkedList.tail.previous.previous.value).toBe(2);
|
||||
expect(linkedList.tail.previous.previous.previous.value).toBe(1);
|
||||
});
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user