简体   繁体   English

从没有 .clear() java 的链表中删除所有元素

[英]remove all elements from a linked list without .clear() java

I want to remove all of the elements in my linked list without using the clear method.我想在不使用clear方法的情况下删除链接列表中的所有元素。

This is my code currently这是我目前的代码

//-----inner class-----
private static class Node <T> { 
  private T data;
  //next just points 
  private Node<T> next; 

  //constructs a node 
  public Node(T data, Node<T> next){ 
     this.data = data; 
     this.next = next; 
  }

  public T getData(){ return data;} 

  public Node<T> getNext(){ return next;}

} }

 private LinkedList<T> theList = new LinkedList<T>();
 private Node<T> head; 
 private Node<T> tail = null;
 private int size=0; 

public ListNoOrder() {
   this.head = null; 
   size = 0; 
}

//an add method 
public void add(T newElt) {
  //if the new element equals null
  //catch the exception
  try{ if (newElt==(null));}
  catch (Exception illegalArgumentException){
     throw new IllegalArgumentException();}

  //if it doesn't catch an exception it adds the element to the list 
  //and increment the size by one 


  //what does the head = new Node<T>(newElt, head) mean??? 
  head = new Node<T>(newElt, head);
  size++; 
}

The reset method that I want to implement If my current list has four objects after calling this method I want that list to have 0 objects我想要实现的重置方法 如果我的当前列表在调用此方法后有四个对象,我希望该列表有 0 个对象

public void reset() {
     head = null;
 }

It should work but everytime I test it says nothing's been deleted.它应该可以工作,但每次我测试它都说没有被删除。 This is just bits and pieces of the complete code.这只是完整代码的一部分。

public void reset() {
     head = null;
 }

(You) (你)

It should work but everytime I test it says nothing's been deleted.它应该可以工作,但每次我测试它都说没有被删除。 This is just bits and pieces of the complete code这只是完整代码的一部分

(My comment) (我的评论)

You remove the reference to the first element of the list so then if are no reference this list exist only in memory of JVM and Garbage Colletor will remove it from memory, but you don't set the size to zero (size=0;) and when test or somthing else will check the list it stil informs that have for eg "size = 6".您删除对列表第一个元素的引用,因此如果没有引用,则此列表仅存在于 JVM 的内存中,垃圾收集器会将其从内存中删除,但您不会将大小设置为零(大小 = 0;)并且当测试或其他东西将检查列表时,它仍然会通知具有例如“size = 6”的列表。 From the other side you have function that is reset your list从另一方面,你有重置你的列表的功能

public ListNoOrder() {
   this.head = null; 
   size = 0; 
}

All comments written in BrokenEnglish :)所有评论都是用 BrokenEnglish 写的 :)

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

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