Tell us what’s happening:
Test output:
// running tests
Cannot read property 'join' of undefined
// tests completed
My own quick console.log bits give the impression i’m successfully reversing the list. I’m passing the
The next and previous references are correctly maintained when a list is reversed.
test, but somehow failing
The reverse method reverses the list.
I’m quite lost on how I could have successfully updated the next and previous references in a reversed list but also fail to reverse the list (according to the test case). The actual test output doesn’t help much (perhaps there’s some other specific test data I can/should use to point me in the right direction?).
Your code so far
var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
this.head = null;
this.tail = null;
// change code below this line
this.reverse = function () {
if(!this.head) return null;
let node = this.head;
this.head = this.tail;
this.tail = node;
while(node) {
let hold = node.next;
node.next = node.prev;
node.prev = hold;
node = node.prev;
}
// console.log('head', this.head.data)
// console.log('tail', this.tail.data)
};
this.add = function(element) {
if(!this.head) {
this.head = new Node(element, null)
this.tail = this.head;
} else {
this.tail.next = new Node(element, this.tail);
this.tail = this.tail.next;
}
}
this.print = () => {
let node = this.head;
while(node) {
console.log(node.data);
node = node.next;
}
};
// change code above this line
};
console.clear();
var x = new DoublyLinkedList();
x.add(1);
x.add(2);
x.add(3);
x.add(4);
x.add('fun')
x.print();
x.reverse();
x.print();
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/reverse-a-doubly-linked-list