2013-04-06 81 views
-3

我正在研究一個簡單的linkedList類,其中一個要求是使用recurs來實現contains方法,add方法和remove方法。Java RecursiveLinkedList包含方法

根據我發現的例子,我已經實現了remove方法,但是包含對我的拋出錯誤。

任何人都可以幫助指出我的包含方法有什麼問題,謝謝&問候。

public class RecursiveLinkedList { 

private int value; 
private RecursiveLinkedList next; 

/* 
* Default Constructor 
* 
* @param value an absolute int value for the current Node 
* @param next an absolute RecursiveLinkedList value for the current Node 
*/ 
public RecursiveLinkedList(int value, RecursiveLinkedList next) { 
    this.value = value; 
    this.next = next; 
} 

/* 
* Constructor Empty, when user supplies an empty for the construcot use 
* value = - 1 and next = null as input parameters 
* 
* @param value an absolute int value for the current Node 
* @param next an absolute RecursiveLinkedList value for the current Node 
*/ 
public static final RecursiveLinkedList EMPTY = new RecursiveLinkedList(-1, null) 
{ 
    public RecursiveLinkedList remove(int n) { return this; }; 

    public String toString() { return ""; }; 
}; 

public RecursiveLinkedList remove(int n) { 
    if (value == n){ 
     return next; 
    } 
    //Call the remove method of the next Node if the selected Node is not the current node 
    return new RecursiveLinkedList(value, next.remove(n)); 
} 

public boolean contains(int n) { 
    if (value == n){ 
     return true; 
    }else if(next == null){ 
     return false; 
    } 
    return new RecursiveLinkedList(value, next).contains(n); 
} 

public String toString() { 
    return value + "," + next.toString(); 
} 

public static void main(String[] args) { 
    RecursiveLinkedList l = new RecursiveLinkedList(1, 
        new RecursiveLinkedList(2, 
        new RecursiveLinkedList(2, 
        new RecursiveLinkedList(3, 
        new RecursiveLinkedList(4, EMPTY))))); 
    System.out.println(" Test to String Method : " + l.toString()); 
    System.out.println(" Test remove method " + l.remove(1).toString()); 
    System.out.println(" Test contains method " + String.valueOf(l.contains(4))); 
} 

}

+0

回覆: 「對含有保持拋出錯誤我」:你看着這個錯誤嗎?你從中學到了什麼? (它是什麼類型的錯誤?什麼信息?它發生什麼行?) – ruakh 2013-04-06 23:57:00

+0

爲什麼你要在每次返回時創建一個新的鏈接列表? – 2013-04-07 00:02:52

+0

感謝您的評論,它在第45行拋出錯誤,我通過創建新實例而不是直接調用下一個對象而犯了錯誤。 – 2013-04-07 02:18:13

回答

0

爲了防止StackOverflowError應改用:

public boolean contains(int n) { 
    if (value == n){ 
     return true; 
    }else if(next == null){ 
     return false; 
    } 
    return next.contains(n); 
} 
+0

非常感謝你指出,是的,我不應該創建一個新的實例。感謝和問候 – 2013-04-07 02:19:06