2013-07-13 81 views
-3

我試圖設計一個鏈接列表的get方法。 它將int位置作爲參數,並返回給定位置處的列表元素(位置從零開始)。鏈接列表使用遞歸方法獲取方法

我認爲我的邏輯是正確的,但沒有編譯。任何人都可以指出我在這裏做錯了什麼嗎?

abstract public class AbstractListNode { 

    abstract public Object first (); 
    abstract public AbstractListNode rest (); 
    abstract public boolean isEmpty (); 
    abstract public int size(); 
    abstract public Object get(int index); 
    // Every other list-processing method goes here. 
} 

class NonemptyListNode extends AbstractListNode { 

    private Object myFirst; 
    private AbstractListNode myRest; 

    // cons in Scheme. 
    public NonemptyListNode (Object first, AbstractListNode rest) { 
     myFirst = first; 
     if (rest == null) { 
     myRest = new EmptyListNode (); 
     } else { 
     myRest = rest; 
     } 
    } 

    public NonemptyListNode (Object first) { 
     this (first, new EmptyListNode ()); 
    } 

    // car in Scheme. 
    public Object first () { 
     return myFirst; 
    } 

    // cdr in Scheme. 
    public AbstractListNode rest () { 
     return myRest; 
    } 

    public boolean isEmpty () { 
    return false; 
    } 

    public int size () { 
     return 1+myRest.size(); 
    } 

    public Object get(int index){ 
     if(index+1 > this.size()) 
      throw new IllegalArgumentException ("Out of Range"); 
     else if(index == 0){ 
      return myFirst; 
     } 
     else{ 
      index = index-1; 
      AbstractListNode l = this.myRest; 
      l.get(index); 
     }   
    } 
} 

class EmptyListNode extends AbstractListNode { 

    public EmptyListNode () { 

    } 

    public Object first () { 
     throw new IllegalArgumentException ("There is no 'first' value stored in an EmptyListNode."); 
    } 

    public AbstractListNode rest () { 
     throw new IllegalArgumentException ("No elements follow an EmptyListNode."); 
    } 

    public boolean isEmpty () { 
     return true; 
    } 

    public int size() { 
     return 0; 
    } 

    public Object get(int index){ 
     throw new IllegalArgumentException ("Out of Range"); 
    } 
} 
+2

如果你得到一個編譯錯誤,你應該真的說出它是什麼以及它會在哪裏出現......這樣我們就不必複製整個代碼並嘗試自己編譯它。 –

+0

_I我認爲我的邏輯是正確的,但不compile_編譯器告訴你哪個行和列有錯誤,你的代碼有哪些錯誤,所以請把它粘貼在這裏。 – BackSlash

+0

對不起。我在NonemptyListNode類的「get方法」中遇到錯誤。 – heeh

回答

3

我在GET方法的錯誤NonemptyListNode

的錯誤是,你沒有return語句:

public Object get(int index){ 
    if(index+1 > this.size()) 
     throw new IllegalArgumentException ("Out of Range"); 
    else if(index == 0){ 
     return myFirst; 
    } 
    else{ 
     index = index-1; 
     AbstractListNode l = this.myRest; 
     l.get(index); 
     /* 
     * here you should have a return statement, if this else block 
     * gets executed, no returns will be found. 
     */ 
    }   
} 
+0

它看起來像if和else語句都應該有return語句。感謝您提供的所有答案和建議。 – heeh