Christopher
Christopher

Reputation: 13

Reverse a linked list... what is wrong with my implementation?

I'm having trouble reversing a linked list based on my implementation below. Is there something wrong or missing that I'm doing here?

class Node {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

class SinglyLinkedList {
    constructor() {
        this.head = null;
        this.length = 0;
    }

    push(val) {
        var newNode = new Node(val);

        var current = this.head; 

        if (!this.head) 
            this.head = newNode; 
        else {

            // iterate to the end of the 
            // list 
            while (current.next) { 
                current = current.next; 
            } 

            // add node 
            current.next = newNode; 
        } 
        this.length++;

        return this; 
    }

    // reverse the list
    reverse() {
        var prev = null;
        var curr = this.head;
        while (curr !== null) {
            var temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }

        return this;
    }

    print() {
        var arr = []
        var current = this.head;

        while(current) {
            arr.push(current.val);
            current = current.next; 
        }

        console.log(arr);
    }
}

Here's my implementation when I create the object and push some nodes

var list = new SinglyLinkedList();
list.push(1);
list.push(2);
list.push(3);
list.push(4);

Every time I ran list.reverse() then list.print() it only prints [1] only and not [4,3,2,1].

Upvotes: 1

Views: 125

Answers (2)

Robin Zigmond
Robin Zigmond

Reputation: 18249

You've not updated the head property in your reverse method. Just add this.head = prev; after the while loop and I believe it should work.

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 84922

You correctly reverse the links between the nodes, but you never change what this.head is pointing at, so it is now pointing at the end of the list instead of the front of the list. So when you call print, print will start at the last node and then have nowhere to go.

  reverse() {
      var prev = null;
      var curr = this.head;
      while (curr !== null) {
          var temp = curr.next;
          curr.next = prev;
          prev = curr;
          curr = temp;
      }
      this.head = prev; // <--- added
      return this;
  }

Upvotes: 3

Related Questions