Linked List使用递归方法获取方法

时间:2013-07-13 22:59:12

标签: java

我试图为链表设计一个get方法。 它将int位置作为参数,并返回给定位置的list元素(position从零开始)。

我认为我的逻辑是对的,但是没有编译。谁能指出我在这里做错了什么?

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");
    }
}

1 个答案:

答案 0 :(得分:3)

  

我在NonemptyListNode

中的get方法出错了

错误是您没有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. 
         */   
    }          
}