简体   繁体   English

Java - 删除整个链表不会影响实际列表

[英]Java - Deleting whole linked-list doesn't affect the actual list

I typed recursive method to delete all the nodes in a simple linked-list but in fact debugger shows this method doesn't affect the actual list and I don't know why it's like that.我输入了递归方法来删除简单链表中的所有节点,但实际上调试器显示此方法不会影响实际列表,我不知道为什么会这样。 Here's my code:这是我的代码:

class List
{ Element root; ...}

class Element
{int value; Element next; ...}


Element delete(Element head)
{
 if(head == null) return null;
 head = delete(head.next);
 return head;
}

There's nothing in your delete method that actually deletes anything, ie it doesn't change the list and it doesn't change any Element in the list.您的 delete 方法中没有任何内容可以实际删除任何内容,即它不会更改列表,也不会更改列表中的任何元素。 All it does is search through the entire list to find an Element whose .next() is null, then it returns null.它所做的只是搜索整个列表以找到 .next() 为 null 的 Element,然后返回 null。

You have to actually change a value somewhere.您必须在某处实际更改一个值。

So let's start with the delete(Element) method.所以让我们从 delete(Element) 方法开始。 As I've come to understand, it needs to take an Element, which is the head of a List, and delete all members of the List.据我了解,它需要取一个 Element,它是 List 的头部,并删除 List 的所有成员。 Setting head = null won't work, as @Dan Getz has noted.正如@Dan Getz 所指出的,设置 head = null 将不起作用。 You need to be able to get at the actual list, and all you have to work with is the Element, so the Element has to know which List contains it.您需要能够获取实际列表,并且您需要处理的只是 Element,因此 Element 必须知道哪个 List 包含它。 And that means you need a myList field of type List in Element.这意味着您需要在 Element 中有一个 List 类型的 myList 字段。 Then your delete(Element head) method could just do然后你的 delete(Element head) 方法就可以了

head.myList.deleteAll();

That requires a deleteAll() method in List, which would set root = null;这需要 List 中的 deleteAll() 方法,它会设置 root = null;

Or, if root is accessible from your delete(Element head) method, you could do或者,如果可以从您的 delete(Element head) 方法访问 root,您可以这样做

head.myList.root = null;

The point is that you somehow have to get to root, and passing it in to some other method doesn't do the job.关键是您必须以某种方式获得 root 权限,并将其传递给其他一些方法并不能完成这项工作。

Old answer below, doesn't quite fit the assignment requirements下面的旧答案,不太符合作业要求

Start by removing the argument.首先删除参数。 You don't need to pass in head.你不需要通过头。

Then, in the body, just set head = null (assuming you have a field called head).然后,在正文中,只需设置 head = null(假设您有一个名为 head 的字段)。

Return either null or the previous value of head, whichever matches your API.返回 null 或 head 的前一个值,以与您的 API 匹配的为准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM