📅  最后修改于: 2023-12-03 15:11:48.910000             🧑  作者: Mango
In Javascript, nodes are often used to represent linked lists. In this guide, we will introduce how to manipulate nodes in linked lists, including adding and deleting nodes.
To add a node to the beginning of a linked list, we can create a new node temp
with the desired value and set its next
pointer to the current head node. We then set the next
pointer of the head node to temp
and set the prev
pointer of the next node to temp
.
let temp = new Node(6, head, head.getNext());
head.setNext(temp);
temp.getNext().setPrev(temp);
Here, head
is the current head node of the linked list. We create a new node with value 6
and set its next
pointer to the current head node's next
pointer. We then set the next
pointer of the head node to temp
, effectively adding temp
to the beginning of the linked list. Finally, we set the prev
pointer of the next node after temp
to temp
.
To delete a node from the end of a linked list, we can set the prev
pointer of the tail node to the node before it, and set the next
pointer of that node to the tail node. We then set the prev
pointer of the tail node's previous node to the tail node's previous node.
let temp1 = tail.getPrev();
tail.setPrev(temp1.getPrev());
temp1.getPrev().setNext(tail);
Here, tail
is the current tail node of the linked list. We create a new node temp1
that points to the node before the tail node. We then set the prev
pointer of the tail node to temp1
's prev
pointer, and set the next
pointer of that node to tail
. This effectively removes temp1
from the list. Finally, we set the prev
pointer of temp1
's previous node to tail
, completing the removal of temp1
from the list.
In summary, node manipulation is an essential skill for managing linked lists in Javascript. With these techniques, you can add and delete nodes with ease.