难以理解反向链表的工作原理

问题描述 投票:0回答:1

我正在反向链接列表。我知道这是一项微不足道的任务,但是我有一个理解上的问题。我在JavaScript中使用了类语法

class LinkedList {
    constructor(value) {
        this.head = {
            value: value,
            next: null
        };
        this.tail = this.head;
        this.length = 1;
    }
    append(value) {
      const newNode = {
        value: value,
        next: null
      }
      this.tail.next = newNode;
      this.tail = newNode;
      this.length++;
      return this;
    }
    reverse() {
      if (!this.head.next) {
        return this.head;
      }
      let first = this.head;
      this.tail = this.head;
      let second = first.next;
      let temp = null

      while(second) {
        temp = second.next;
        second.next = first;
        first = second;
        second = temp;

        console.log('first', first)
      }

      this.head.next = null;
      console.log('first after', first)
      this.head = first;
      return this
    }
}
let myLinkedList = new LinkedList(5);
myLinkedList.append(1)
myLinkedList.append(99)
myLinkedList.reverse()

我不明白的是:在while循环的最后一次迭代之后,first变量应指向该对象(它是console.log('first', first)):

{ value: 99,
  next: { value: 1, next: { value: 5, next: [Circular] } } } 

但是,循环结束后,first开始指向这个,这给了我们正确的答案(console.log('first after', first))

{ value: 99,
  next: { value: 1, next: { value: 5, next: null } } }

我什至试图绘制图表,但仍然无法理解为什么会发生([first.next.next.next为什么开始指向null)

javascript linked-list reverse
1个回答
1
投票

是因为this.head.next = null;行。first.next.next.nextthis.head指向同一个节点:5

下面是您的代码,带有一些额外的注释:

    reverse() {
      // At the start of the invocation, the linked list will be:
      // head: 5
      // (mid): 1
      // tail: 99

      if (!this.head.next) {
        return this.head;
      }
      let first = this.head;
      this.tail = this.head;
      let second = first.next;
      let temp = null

      while(second) {
        temp = second.next;
        second.next = first;
        first = second;
        second = temp;

        console.log('first', first)
      }

      // At this point, the `next` pointer of each node is updated together
      // with `this.tail`, but `this.head` still refers to the previous head (now tail).
      // `this.head` and `first.next.next.next` reference the same node '5'.

      this.head.next = null;
      console.log('first after', first)

      // Only after this assignment will the head be updated, resulting in the following linked list:
      // head: 99
      // (mid): 1
      // tail: 5
      this.head = first;

      return this
    }
© www.soinside.com 2019 - 2024. All rights reserved.