2013-07-13 55 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