From 5e17d7681741ead2c2de1b9f371114de2ad4b6e5 Mon Sep 17 00:00:00 2001 From: Manish Date: Sat, 26 Aug 2023 12:11:52 +1000 Subject: [PATCH] Data Structures: Reverse a Doubly Linked List --- Data Structures/doublyLinkedListReverse.js | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Data Structures/doublyLinkedListReverse.js diff --git a/Data Structures/doublyLinkedListReverse.js b/Data Structures/doublyLinkedListReverse.js new file mode 100644 index 0000000..cf3f251 --- /dev/null +++ b/Data Structures/doublyLinkedListReverse.js @@ -0,0 +1,25 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/reverse-a-doubly-linked-list + +var Node = function (data, prev) { + this.data = data; + this.prev = prev; + this.next = null; +}; +var DoublyLinkedList = function () { + this.head = null; + this.tail = null; + // Only change code below this line + this.reverse = () => { + const newTail = this.head; + let node = this.head; + while (node !== null) { + const newPrev = node.next; + node.next = node.prev; + node.prev = newPrev; + node = newPrev; + } + this.head = this.tail; + this.tail = newTail; + }; + // Only change code above this line +};