如何通过递归显示链接列表中的元素?

时间:2018-02-23 11:41:10

标签: java recursion linked-list

你好这是我的链表而没有实现java.util.linkedlist

我想创建一个方法,递归显示我链接列表中的所有元素,但我不知道如何,我的方法没有任何参数,所以我不知道如何到达下一个调用方法本身时的值

    public class Pokemon {
        private String name;
        private String type;
        private int niveau;

        public Pokemon(String name, String type) {
            this.name = name;
            this.type = type;
            this.niveau = (int) (Math.random() * (1 * 1 - 100) + 100);
        }
        public void display() {
            System.out.println(this.name);
       }

    public class Trainer {

        public final String name;
        private Pokeball head;

        public Trainer(String name) {
            this.name = name;
        }

        public void addPokemon(Pokemon pok) {
            if (this.head != null) {
                this.head.addPokemon(pok);
            } else {
                this.head = new Pokeball(pok);
            }
        }

       public void display() {
            if (this.head == null)
        return;
    else {
        this.head.display();
    }


    }

    public class Pokeball {

        private Pokemon pok;
        private Pokeball next;

        public Pokeball(Pokemon pok) {
            this.pok = pok;
        }

        public Pokeball(Pokemon pok, Pokeball next) {
            this.pok = pok;
            this.next = next;
        }

        public void addPokemon(Pokemon pok) {
            Pokeball current = this;
            while (current.next != null) {
                current = current.next;
            }
            current.next = new Pokeball(pok);
        }

public void display() {
    Pokeball current = this;
    if (current.next == null){
        return;
    } else { 
        // ....
    }


    }

2 个答案:

答案 0 :(得分:1)

我认为这是针对Pokeball类的,为什么要使用递归显示?为什么不迭代?您的Trainer课程没有创建链接列表,但没有next

public void display() {
    Pokeball current = this; //Note that this won't change your 'this'
    while ( current != null ) {
        System.out.print( current.display() + "->" );
        current = current.next;
    }
}

递归:

private void display_recurse( Pokeball current ) {
    if ( current == null )
      return;
    System.out.print( current.display() + "->" );
    display_recurse( current.next);
}

你可以这样称呼:

public void display() {
   display_recurse( this );
}

答案 1 :(得分:1)

通常这是使用具有参数的私有帮助函数来完成的。

public void display() {
    Pokeball current = this;
    display(current);
}

private void display(Pokeball toDisplay) {
    if(toDisplay == null) {
        return;
    } else {
        // code to display current here
        // ...
        display(toDisplay.next);
    }
}
相关问题