java - 使用递归反转链表生成错误的输出

标签 java linked-list

我的反转链表的递归方法有问题吗?因为我得到以下输出,在反转后仅打印 1 个:

原始链表: 1-->2-->3-->4-->5-->尾部

使用递归的反向链表: 1-->尾部

public class ReverseList {

    public static List ReverseRecursion(List head){


        List current = head;

        if(current == null){
            return null;
        }
        if(current.next == null){
            head = current;
            return head;
        }
        ReverseRecursion(current.next);
        current.next.next = current;
        current.next = null;
        return head;

    }



    public static void main (String[] args){

    // Created a Single LinkedList

    List myList = new List(1);
    myList.next = new List(2);
    myList.next.next = new List(3);
    myList.next.next.next = new List(4);
    myList.next.next.next.next = new List(5);

    System.out.println("Original LinkedList: \n"+myList.toString());



    System.out.println("Reversed LinkedList Using Recursion: \n"+ReverseRecursion(myList));

    }
}

class List {
    int value;
    List next;
    public List(int k){
        value = k;
        next = null;
    }

    public String toString(){

        List cur = this;
        String output = "";
        while(cur != null){

            output+=cur.value+"-->";
            cur = cur.next;
        }
        return output+"Tail";


    }

}

最佳答案

ReverseRecursion中, 你永远不会将反向列表分配回head。 更改此行:

ReverseRecursion(current.next);

对此:

head = ReverseRecursion(current.next);

关于java - 使用递归反转链表生成错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466192/

相关文章:

java - 基于Java中的类变量对用户定义对象的2个LinkedList进行自定义排序

java - 向 KeyListener 添加计时器

java - 是否有带有 Java 监听器的 Map 实现?

java - 使用 Java 8,创建排序和分组字符串列表的最简洁方法是什么

java - Hibernate native 查询可选参数抛出 'operator does not exist: bigint = bytea'

java - 更新链表

algorithm - Runner 技术组合两个相等的链表

java - 如何为后续与 HttpClient 的连接存储 cookie

python - 循环链表代码陷入无限循环

c - 尝试从排序列表创建新链表时出现段错误 11