使用 JavaScript 将元素插入双向链表


我们需要创建一个函数 insert(data, position),该函数在链表的给定位置插入数据。我们将执行以下步骤:

  • 创建一个新的节点
  • 检查列表是否为空。如果是,则将节点添加到头部和尾部并返回。
  • 如果不是,我们将使用 currElem 迭代到我们想要插入的位置。我们通过使 currElem 等于 currElem.next 来迭代链表。

现在,我们将以以下方式更改链接:

  • 使新节点指向列表中的下一个节点
  • 使下一个节点的上一个指向新节点
  • 使我们的节点指向前一个节点
  • 使前一个节点的下一个指向新节点

最后,我们断开 currElem 与列表其余部分的链接,并使其指向我们创建的节点。现在,该节点位于列表中给定位置。

这是一个相同的示例:

现在让我们看看我们将如何实现它:

示例

insert(data, position = this.length) {
   let node = new this.Node(data);
   this.length++;
   // List is currently empty
   if (this.head === null) {
      this.head = node;
      this.tail = node;
      return this.head;
   }
   // Insertion at head
   if (position == 0) {
      node.prev = null;
      node.next = this.head;
      this.head.prev = node;
      this.head = node;
      return this.head;
   }
   let iter = 1;
   let currNode = this.head;
   while (currNode.next != null && iter < position) {
      currNode = currNode.next;
      iter++;
   }
   // Make new node point to next node in list
   node.next = currNode.next;
   // Make next node's previous point to new node
   if (currNode.next != null) {
      currNode.next.prev = node;
   }
   // Make our node point to previous node
   node.prev = currNode;
   // Make previous node's next point to new node
   currNode.next = node;
   // check if inserted element was at the tail, if yes then make tail point to it
   if (this.tail.next != null) {
      this.tail = this.tail.next;
    }
    return node;
}

请注意,我们已将位置指定为最后一个元素。这是因为,如果您不提供位置,则默认情况下它将插入到末尾。

您可以使用以下方法进行测试:

示例

let list = new LinkedList();
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(15, 2);
list.display();

输出

这将给出以下输出:

10 <->
30 <->
15 <->
20 <->

正如我们所看到的,所有元素都按我们预期的顺序排列。我们尝试在 2 之后的位置插入 15。

更新于: 2020年6月15日

447 次查看

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.