Reversing a Doubly Linked List

Hey there, so I wrote a reverse method for my doubly linked list, tested it independently outside of FCC and saw that it worked. However, when I test it in FCC, I get the errors: > The reverse method reverses the list.

The next and previous references are correctly maintained when a list is reversed.

I’ve tested it and my reverse method does indeed reverse the list. My code for the problem is here:

var Node = function(data, prev) {
  this.data = data;
  this.prev = prev;
  this.next = null;
};
var DoublyLinkedList = function() {
  this.head = null;
  this.tail = null;
  this.length = 0;
  var length = this.length;
  // change code below this line
  this.reverse = function(){

  	if(length == 0){
  		return null;
  	}
  	else if(length > 1){
  		let currNode = this.head;
  		let prevNode = null;
  		let nextNode = null;

  		for(let i = 0; i < length; i++){
  			prevNode  = currNode.prev;
  			nextNode = currNode.next;

  			if(prevNode == null){
  				this.tail = currNode;
  				currNode.next = null;
  				currNode.prev = nextNode;
  			}
  			else if(nextNode == null){
  				this.head = currNode;
  				currNode.prev = null;
  				currNode.next = prevNode;
  			}
  			else{
  				currNode.next = prevNode;
  				currNode.prev = nextNode;
  			}

  			currNode = nextNode;
  		}
  	}
  }
  // change code above this line
};

Hello Mingyuea,

I couldn’t able to spot the bug in your code but I could help you with my accepted solution and here it goes.

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.add = function(element) {
    if (this.head === null) {
      let node = new Node(element);

      this.head = node;
      this.tail = node;
    } else {
      let currentNode = this.head;

      while (currentNode.data !== element) {
        if (currentNode.next !== null) {
          currentNode = currentNode.next;
        } else {
          break;
        }
      }
      let node = new Node(element, currentNode);
      currentNode.next = node;
      this.tail = node;
    }
  };
  this.reverse = function() {
    if (this.head === null) {
      return null;
    }

    let currentNode = this.head;
    this.tail = currentNode;

    while (currentNode !== null) {
      let prev = currentNode.prev;
      currentNode.prev = currentNode.next;
      currentNode.next = prev;

      if (currentNode.prev) {
        currentNode = currentNode.prev;
      } else {
        this.head = currentNode;
        break;
      }
    }
  };
  // change code above this line
};

Also, I recommend you use while instead of for loop.
Thank you.

mingyuea, your problem in this.length property. Tests doesn’t know about this. Instead you should check this.head for null like BalasubramaniM