From 3ee1c39e41c1aae3b0b23b3e79fba3ec1aae1989 Mon Sep 17 00:00:00 2001 From: Keith Warter Date: Thu, 26 Mar 2020 21:01:49 -0700 Subject: [PATCH] Adding a solution for reversing a DoubleLinkedList. (#38427) --- .../reverse-a-doubly-linked-list.english.md | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/curriculum/challenges/english/08-coding-interview-prep/data-structures/reverse-a-doubly-linked-list.english.md b/curriculum/challenges/english/08-coding-interview-prep/data-structures/reverse-a-doubly-linked-list.english.md index 08a4650c9e..30cd037a37 100644 --- a/curriculum/challenges/english/08-coding-interview-prep/data-structures/reverse-a-doubly-linked-list.english.md +++ b/curriculum/challenges/english/08-coding-interview-prep/data-structures/reverse-a-doubly-linked-list.english.md @@ -122,7 +122,35 @@ DoublyLinkedList.prototype = Object.assign(
```js -// solution required + var Node = function(data, prev) { + this.data = data; + this.prev = prev; + this.next = null; + }; + var DoublyLinkedList = function() { + this.head = null; + this.tail = null; + + this.reverse = function() { + if (!this.head || !this.head.next) { + return this.head + } + + let tail; + let temp; + let current = this.head; + while(current !== null) { + if(!tail) tail = current; + temp = current.prev; + current.prev = current.next; + current.next = temp; + current = current.prev; + } + + this.head = temp.prev; + this.tail = tail + } + }; ```