Java:删除链接列表中的所有元素

时间:2020-12-04 07:16:36

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.

在Java中,如何在不使用已有的clear()方法的情况下删除链表中的所有元素?这项练习的灵感来自于电话采访中收到的问题。

Say I can do this in C

说我可以用C做到这一点

void DeleteAllElement( ListElement **head ) {  
    ListElement *deleteMe = *head;  
    while( deleteMe )  {  
        ListElement *next = deleteMe->next;  
        delete deleteMe;  
        deleteMe = next;  
    }  
    *head = NULL;  
}

Thanks

谢谢

4 个解决方案

#1


11  

Java has automatic garbage collection, so you just need to set the Head reference to null:

Java具有自动垃圾收集功能,因此您只需将Head引用设置为null:

myList.headNode = null;

myList.headNode = null;

So, let's say we have the class LinkedList, which also has a resetList function...

所以,假设我们有类LinkedList,它也有一个resetList函数......

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();}
}

If we are not making the head node private, we could simply execute the first code snippet I posted.

如果我们不将头节点设为私有,我们可以简单地执行我发布的第一个代码片段。

#2


8  

If you are talking about an instance of java.util.LinkedList:

如果您正在讨论java.util.LinkedList的实例:

    while (!linkedlist.isEmpty()) {
        linkedlist.removeFirst();
    }

If you are talking about an instance of any java.util.List:

如果您正在讨论任何java.util.List的实例:

    while (!list.isEmpty()) {
        list.remove(0);
    }

bearing in mind that remove is an optional operation. However, depending on the list implementation, that could be horribly in efficient. For an ArrayList this would be better:

请记住,删除是一项可选操作。但是,根据列表实现,这可能非常有效。对于ArrayList,这会更好:

    while (!list.isEmpty()) {
        list.remove(list.size() - 1);
    }

Another alternative would be to iterate the list and call Iterator.remove() on each element ... also an optional operation. (But once again, that could be horribly inefficient for some list implementations.)

另一种方法是迭代列表并在每个元素上调用Iterator.remove()...也是一个可选操作。 (但是,对于某些列表实现,这可能会非常低效。)

If you are talking about a custom linked list class, then the answer depends on the way you have declared the list classes internal data structures.

如果您正在讨论自定义链接列表类,那么答案取决于您声明列表类内部数据结构的方式。


I suspect that if the interviewers mentioned the clear() method, they were expecting an answer in the context of the standard Java collection framework ... not a custom linked list class.

我怀疑如果访调员提到了clear()方法,他们期望在标准Java集合框架的上下文中得到答案......而不是自定义链表类。

#3


1  

Reading the actual code is useful. I suggest you have a look.

阅读实际代码很有用。我建议你看看。

For a singly linked list you can just do as @bdares, suggests when you look at the actual code for java.util.LinkedList (Which is what most developers use), the answer is rather different.

对于单链表,您可以像@bdares那样做,建议您在查看java.util.LinkedList的实际代码时(这是大多数开发人员使用的),答案是相当不同的。

public void clear() {
    Entry<E> e = header.next;
    while (e != header) {
        Entry<E> next = e.next;
        e.next = e.previous = null;
        e.element = null;
        e = next;
    }
    header.next = header.previous = header;
    size = 0;
    modCount++;
}

First thing to note; this is doubly linked list for forward and backward traversal and it agressively clears all the references. Not sure why it does this to be honist because the GC will clear thes eup any way and the modCount will pick up any changes in another thread. In fact it should really perform the modCount first.

首先要注意的是;这是前向和后向遍历的双重链表,它积极清除所有引用。不确定为什么要这样做是因为GC会以任何方式清除eup并且modCount将在另一个线程中获取任何更改。实际上它应该首先执行modCount。

For comparison, here is ArrayList.clear();

为了比较,这里是ArrayList.clear();

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

#4


1  

for(i=0;i<linkedlist.size;i++){
  linkedlist.removeFirst();
}

or see this example.

或者看这个例子。

#1


11  

Java has automatic garbage collection, so you just need to set the Head reference to null:

Java具有自动垃圾收集功能,因此您只需将Head引用设置为null:

myList.headNode = null;

myList.headNode = null;

So, let's say we have the class LinkedList, which also has a resetList function...

所以,假设我们有类LinkedList,它也有一个resetList函数......

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();}
}

If we are not making the head node private, we could simply execute the first code snippet I posted.

如果我们不将头节点设为私有,我们可以简单地执行我发布的第一个代码片段。

#2


8  

If you are talking about an instance of java.util.LinkedList:

如果您正在讨论java.util.LinkedList的实例:

    while (!linkedlist.isEmpty()) {
        linkedlist.removeFirst();
    }

If you are talking about an instance of any java.util.List:

如果您正在讨论任何java.util.List的实例:

    while (!list.isEmpty()) {
        list.remove(0);
    }

bearing in mind that remove is an optional operation. However, depending on the list implementation, that could be horribly in efficient. For an ArrayList this would be better:

请记住,删除是一项可选操作。但是,根据列表实现,这可能非常有效。对于ArrayList,这会更好:

    while (!list.isEmpty()) {
        list.remove(list.size() - 1);
    }

Another alternative would be to iterate the list and call Iterator.remove() on each element ... also an optional operation. (But once again, that could be horribly inefficient for some list implementations.)

另一种方法是迭代列表并在每个元素上调用Iterator.remove()...也是一个可选操作。 (但是,对于某些列表实现,这可能会非常低效。)

If you are talking about a custom linked list class, then the answer depends on the way you have declared the list classes internal data structures.

如果您正在讨论自定义链接列表类,那么答案取决于您声明列表类内部数据结构的方式。


I suspect that if the interviewers mentioned the clear() method, they were expecting an answer in the context of the standard Java collection framework ... not a custom linked list class.

我怀疑如果访调员提到了clear()方法,他们期望在标准Java集合框架的上下文中得到答案......而不是自定义链表类。

#3


1  

Reading the actual code is useful. I suggest you have a look.

阅读实际代码很有用。我建议你看看。

For a singly linked list you can just do as @bdares, suggests when you look at the actual code for java.util.LinkedList (Which is what most developers use), the answer is rather different.

对于单链表,您可以像@bdares那样做,建议您在查看java.util.LinkedList的实际代码时(这是大多数开发人员使用的),答案是相当不同的。

public void clear() {
    Entry<E> e = header.next;
    while (e != header) {
        Entry<E> next = e.next;
        e.next = e.previous = null;
        e.element = null;
        e = next;
    }
    header.next = header.previous = header;
    size = 0;
    modCount++;
}

First thing to note; this is doubly linked list for forward and backward traversal and it agressively clears all the references. Not sure why it does this to be honist because the GC will clear thes eup any way and the modCount will pick up any changes in another thread. In fact it should really perform the modCount first.

首先要注意的是;这是前向和后向遍历的双重链表,它积极清除所有引用。不确定为什么要这样做是因为GC会以任何方式清除eup并且modCount将在另一个线程中获取任何更改。实际上它应该首先执行modCount。

For comparison, here is ArrayList.clear();

为了比较,这里是ArrayList.clear();

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

#4


1  

for(i=0;i<linkedlist.size;i++){
  linkedlist.removeFirst();
}

or see this example.

或者看这个例子。