【问题标题】:Reverse Linked List using Iteration in Javascript在Javascript中使用迭代反向链接列表
【发布时间】:2017-10-02 12:01:01
【问题描述】:

我得到了所需的输出,即下面console.log 中第三次迭代的反向链表。

但我有 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);

【问题讨论】:

  • 你永远不会把this.head设置到另一边
  • 您的确切问题与标题无关。也许你应该改变它。
  • 我已回滚您的编辑。当您找到解决方案时,请post an answer 而不是编辑问题。
  • @Bergi,我如何设置this.head
  • @DhavalJardosh 分配给它。

标签: javascript algorithm linked-list


【解决方案1】:

它在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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2020-02-06
    • 2016-01-22
    相关资源
    最近更新 更多