删除链接列表中的所有元素而不使用.clear()java

时间:2017-03-08 17:09:31

标签: java linked-list

我想删除链接列表中的所有元素,而不使用clear方法。

这是我目前的代码

//-----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++; 
}

我想要实现的重置方法 如果我的当前列表在调用此方法后有四个对象,我希望该列表具有0个对象

public void reset() {
     head = null;
 }

它应该可以工作,但每次我测试它都说什么都没有被删除。这只是完整代码的一点一滴。

1 个答案:

答案 0 :(得分:0)

public void reset() {
     head = null;
 }

(你)

它应该可以工作,但每次我测试它都说没有删除任何东西。这只是完整代码的一点一滴

(我的评论)

删除对列表第一个元素的引用,如果没有引用,则此列表仅存在于JVM的内存中,Garbage Colletor会将其从内存中删除,但是不要将大小设置为零(size = 0;)当测试或其他东西将检查列表时,它会通知例如“size = 6”。从另一方面,你有重置列表的功能

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

用BrokenEnglish写的所有评论:)