简体   繁体   中英

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] .

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;
  }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM