java - 如何通过递归显示链表中的元素?

标签 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 { 
        // ....
    }


    }

最佳答案

我假设这是用于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 );
}

关于java - 如何通过递归显示链表中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48947053/

相关文章:

c - 为什么当我修改函数内部的链表时会出现段错误?

c++ - 二叉树中的递归搜索

c++ - 将字符串解析为int

java - 非常大的 Java ArrayList 遍历时间很慢

java - SQLite 异常 : near "CREATE": syntax error (code 1)

c++ - 递归的最坏情况时间复杂度

java - 如何修复此堆栈溢出错误?

java - 如何检查 GSON 元素的空值?

Java:我收到一个类转换异常错误,指向我什至没有导入的类

java.lang.IllegalArgumentException : Illegal character in authority at index 7 while making https request 异常