使用Javascript中的迭代反向链接列表

时间:2017-10-02 12:01:01

标签: javascript algorithm linked-list

我正在获得所需的输出,即下面console.log中第3次迭代的反向链表。

但我有return previous,它仍然会返回第一次迭代的值。

即使console.log(previous)代替return previous,也会提供所需的输出。

但现在的问题是如何最终显示它?

有人可以解释一下,出了什么问题?

  reverse(){
      var current= this.head,previous=null;
      while(current)
      {
        var next = current.next;
        current.next = previous;
        previous = current;
        current = next;
        console.log(previous); //I am getting my answer at the third iteration
      }
      return previous; //
  }



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

  add(value) {
    var node = new Node(value);
    if (this.head == null) {
      this.head = node;
      this.length++;
    } else {
      var current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = node;
      this.length++;
    }
  }

  reverse() {
    var current = this.head,
      previous = null;
    while (current) {
      var next = current.next;
      current.next = previous;
      previous = current;
      current = next;
      console.log(previous);
    }
    return previous;
  }
}

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

var ll = new LinkedList();

ll.add(3);
ll.add(2);
ll.add(7);

ll.reverse();
console.log(ll.head);




1 个答案:

答案 0 :(得分:0)

它在return previous

上提供了所需的输出

所需要的只是为此特定问题调用函数ll.reverse()console.log(ll.reverse())

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

  add(value) {
    var node = new Node(value);
    if (this.head == null) {
      this.head = node;
      this.length++;
    } else {
      var current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = node;
      this.length++;
    }
  }

  reverse() {
    var current = this.head,
      previous = null;
    while (current) {
      var next = current.next;
      current.next = previous;
      previous = current;
      current = next;
    }
    return previous;
  }
}

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

var ll = new LinkedList();

ll.add(3);
ll.add(2);
ll.add(7);
ll.add(9);
console.log(ll.reverse());