Java:删除链表中的所有元素 [英] Java:Delete all the elements from Linked List
本文介绍了Java:删除链表中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在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屋!
查看全文