fixed doubly-linked-list reverse method omit change node's previous (#257)

This commit is contained in:
YuqiangZhang 2018-12-09 23:03:47 +08:00 committed by Oleksii Trekhleb
parent 4e27a979d7
commit c18d119a6a
2 changed files with 30 additions and 7 deletions

View File

@ -243,9 +243,11 @@ export default class DoublyLinkedList {
while (currNode) { while (currNode) {
// Store next node. // Store next node.
nextNode = currNode.next; nextNode = currNode.next;
prevNode = currNode.previous;
// Change next node of the current node so it would link to previous node. // Change next node of the current node so it would link to previous node.
currNode.next = prevNode; currNode.next = prevNode;
currNode.previous = nextNode;
// Move prevNode and currNode nodes one step forward. // Move prevNode and currNode nodes one step forward.
prevNode = currNode; prevNode = currNode;

View File

@ -236,22 +236,43 @@ describe('DoublyLinkedList', () => {
linkedList linkedList
.append(1) .append(1)
.append(2) .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.head.value).toBe(1);
expect(linkedList.tail.value).toBe(3); expect(linkedList.tail.value).toBe(4);
// Reverse linked list. // Reverse linked list.
linkedList.reverse(); linkedList.reverse();
expect(linkedList.toString()).toBe('3,2,1'); expect(linkedList.toString()).toBe('4,3,2,1');
expect(linkedList.head.value).toBe(3);
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.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. // Reverse linked list back to initial state.
linkedList.reverse(); 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.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);
}); });
}); });