【问题标题】:remove all elements from a linked list without .clear() java从没有 .clear() java 的链表中删除所有元素
【发布时间】:2017-07-29 09:20:15
【问题描述】:

我想在不使用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;
 }

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

【问题讨论】:

  • 这是java.util.LinkedList还是你自己的实现?
  • 您的问题文字与您的标题完全相反?!
  • @Jeremy 我自己的实现
  • @GhostCat 我的错误哎呀
  • @lionbear28 向我们展示您是如何确定这一点的。蝙蝠的权利,你没有将size 变量更改为0...

标签: java linked-list


【解决方案1】:
public void reset() {
     head = null;
 }

(你)

它应该可以工作,但每次我测试它都说没有被删除。这只是完整代码的零碎部分

(我的评论)

您删除了对列表第一个元素的引用,因此如果没有引用,则此列表仅存在于 JVM 的内存中,垃圾收集器将从内存中删除它,但您没有将大小设置为零(大小 = 0;) 并且当测试或其他东西将检查它仍然通知的列表时,例如“size = 6”。从另一边你有重置你的列表的功能

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

所有的 cmets 都是用 BrokenEnglish 写的 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2017-03-25
    • 2013-12-17
    相关资源
    最近更新 更多