[英]Deleting a node in the middle of a single linkedlist
I have written a program that removes a node in the single linkedlist given the node.我编写了一个程序,可以在给定节点的单个链表中删除一个节点。
public class Solution {
/**
* @param node: the node in the list should be deleted
* @return: nothing
*/
public void deleteNode(ListNode node) {
// write your code here
// if node.next==null, we cannot delete the current node without given the previous node
if(node == null || node.next == null) return;
ListNode next = node.next;
node.val = next.val;
node.next = next.next;
// I wonder if this link needs to be removed as well
next.next = null;
}
}
The problem is pretty simple.问题很简单。 However, many code samples online do not contain this line I wrote:但是,网上很多代码示例都没有我写的这行:
next.next = null;
Without this line, we already remove the node.没有这一行,我们已经删除了节点。 After that, although nothing is pointing to "next", "next" still points to next.next.之后,虽然没有任何东西指向“next”,但“next”仍然指向next.next。 Without setting next.next = null, will the Java garbage collector remove this deleted node?不设置next.next = null,Java垃圾回收器会不会删除这个被删除的节点?
Indeed it will.确实会。 The gc iterates over all objects and checks wether someone else points to it. gc 遍历所有对象并检查其他人是否指向它。 If not, it is marked for deletion.如果不是,则将其标记为删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.