我曾经遇到过这样的问题:
previous
是 current 的前一个节点。 current
是我们正在查看的当前节点。
这就是 prev.next
指向 current 之后的元素。
prev.next = current.next;
但是,我忘记了为什么这不起作用,我们必须这样做:
Node temp = current.next;
prev.next = temp;
current = temp;
最佳答案
Why do we need a temp variable to delete a node from a linked list
自从您从元素中删除引用
您不需要像下面的代码中那样的临时变量来释放从当前到下一个的链接。
prev.next = current.next;
current.next = null; // release this link
current = null; // optional
删除后,我们得到:current
未被前一个节点引用,并且 current.next
为 null
。
因为linkedList是一个列表,其中每个元素都有一个到下一个元素的链接(实际上,它也有一个到前一个元素的链接)。
因此,与 ArrayList 相比,从列表中删除元素非常容易,其中元素存储在数组中,删除元素意味着移动数组中后面的每个元素。
In computer science, a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a data and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence.
请参阅此处Linked List
关于java - 为什么我们需要一个临时变量来从链表中删除节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18201065/