Java:删除链接列表中的所有元素 [英] Java:Delete all the elements from Linked List
问题描述
在Java中,如何使用已经可用的 clear()
方法删除链接列表中没有的所有元素?这个练习的灵感来自于电话采访中收到的一个问题。
In Java, how to remove all the elements in linked list without using already available clear()
method? This exercise was inspired by a question received in a phone interview.
我可以用C语言做这个。
Say I can do this in C
void DeleteAllElement( ListElement **head ) {
ListElement *deleteMe = *head;
while( deleteMe ) {
ListElement *next = deleteMe->next;
delete deleteMe;
deleteMe = next;
}
*head = NULL;
}
谢谢
推荐答案
Java有自动垃圾回收,所以你只需要将Head引用设置为null:
Java has automatic garbage collection, so you just need to set the Head reference to null:
myList .headNode = null;
所以,假设我们有类 LinkedList
,它还有一个 resetList
函数...
So, let's say we have the class LinkedList
, which also has a resetList
function...
public class LinkedList{
private Node head;
public Node find(Key k){ ... }
public void add(Node n){ ... }
...
public void reset(){ head = null;}
public static void reset(LinkedList l){l.reset();}
}
如果我们没有将 head
节点设为私有,我们可以简单地执行我发布的第一个代码片段。
If we are not making the head
node private, we could simply execute the first code snippet I posted.
这篇关于Java:删除链接列表中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!