2017-03-08 140 views
-3

我想刪除鏈接列表中的所有元素,而不使用clear方法。從.clear()刪除鏈接列表中的所有元素java

這是我的代碼目前

//-----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 objects

public void reset() { 
    head = null; 
} 

它應該工作,但每次我測試它說沒有東西被刪除。這只是完整代碼的一小部分。

+2

這是'java.util.LinkedList'或您自己的實現? – Jeremy

+1

您的問題文字與您的標題完全相反? – GhostCat

+0

@Jeremy我自己的實現 – lionbear28

回答

0
public void reset() { 
    head = null; 
} 

(你)

它應該工作,但每次我測試它說什麼也沒有被刪除。這只是位和完整的代碼片段

(我的意見)

你,如果沒有參考這份名單隻在JVM和垃圾Colletor的內存中刪除引用到列表的第一個元素是的話會將其從內存中移除,但是您不會將大小設置爲零(大小= 0;),並且當測試或其他東西會檢查列表時,它會通知例如「大小= 6」的列表。從你有功能的另一面就是重置您的列表

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

寫在BrokenEnglish所有評論:)