我正在用 JS 编写一个链表,但我编写的前置函数没有按我的预期工作

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

所以我的初始代码如下所示:

class LinkedList {
  constructor() {
    this.head = new Node(-1);
    this.tail = this.head;
  };
  prepend(value) {
    let next = this.head.nextNode;
    this.head = new Node(value);
    this.head.nextNode = next;
  };
};

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

假设我要在前面添加一个值 1,然后在前面添加另一个值 2。输出将如下所示:

LinkedList = {
  head: {
    nextNode: null,
    value: 2
  },
  tail: {
    nextNode: null,
    value: -1
  }
};

这并不是我真正想要的。相反,我希望 head 的值等于 2,然后让 head 指向一个值为 1 的新节点。

我对如何解决这个问题感到非常困惑,我不想只是查找答案,因为在第一次学习这个概念后,我正在尝试学习如何自己实现这样的东西。如果我能得到任何帮助,我将不胜感激。我希望您能给我一个提示,将我推向正确的方向,然后在下面提出正确的方法来解决这个问题,因为我仍然在不查找答案的情况下解决这个问题。预先感谢!

javascript data-structures linked-list
1个回答
0
投票

class LinkedList {
  constructor() {
  
  };
  prepend(value) {
    this.head = new Node(value, this.head);
    this.tail || (this.tail = this.head);
  };
};

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

const list = new LinkedList;

list.prepend(1);
list.prepend(2);

console.log(JSON.stringify(list, null, 4));

© www.soinside.com 2019 - 2024. All rights reserved.