Java 使用递归反转linkedlist生成错误输出

Java 使用递归反转linkedlist生成错误输出,java,linked-list,Java,Linked List,我的递归方法反转linkedlist是否有问题?因为我得到以下输出,反转后仅打印1: 原始链接列表: 1-->2-->3-->4-->5-->尾部 使用递归反向链接列表: 1-->尾部 在反向诅咒中, 您永远不会将反向列表分配回标题。 更改此行: ReverseRecursion(current.next); 为此: head = ReverseRecursion(current.next); 在反向诅咒中, 您永远不会将反向列表分配回标题。 更改此行: ReverseRecursion(c

我的递归方法反转linkedlist是否有问题?因为我得到以下输出,反转后仅打印1:

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

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


反向诅咒中
, 您永远不会将反向列表分配回
标题
。 更改此行:

ReverseRecursion(current.next);
为此:

head = ReverseRecursion(current.next);

反向诅咒中
, 您永远不会将反向列表分配回
标题
。 更改此行:

ReverseRecursion(current.next);
为此:

head = ReverseRecursion(current.next);

反向诅咒中
, 您永远不会将反向列表分配回
标题
。 更改此行:

ReverseRecursion(current.next);
为此:

head = ReverseRecursion(current.next);

反向诅咒中
, 您永远不会将反向列表分配回
标题
。 更改此行:

ReverseRecursion(current.next);
为此:

head = ReverseRecursion(current.next);

您离使用代码不远:

public static List ReverseRecursion(List head){
    List newHead;

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

    newHead = ReverseRecursion(head.next);
    head.next.next = head;
    head.next = null;
    return newHead;
}


要点:

  • 您根本不需要
    current
    head
    是不可变的
  • 您应该返回(和propegate)“新头”,从最深的递归调用开始,一直到递归结束

  • 您离使用代码不远:

    public static List ReverseRecursion(List head){
        List newHead;
    
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
    
        newHead = ReverseRecursion(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
    


    要点:

  • 您根本不需要
    current
    head
    是不可变的
  • 您应该返回(和propegate)“新头”,从最深的递归调用开始,一直到递归结束

  • 您离使用代码不远:

    public static List ReverseRecursion(List head){
        List newHead;
    
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
    
        newHead = ReverseRecursion(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
    


    要点:

  • 您根本不需要
    current
    head
    是不可变的
  • 您应该返回(和propegate)“新头”,从最深的递归调用开始,一直到递归结束

  • 您离使用代码不远:

    public static List ReverseRecursion(List head){
        List newHead;
    
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
    
        newHead = ReverseRecursion(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
    


    要点:

  • 您根本不需要
    current
    head
    是不可变的
  • 您应该返回(和propegate)“新头”,从最深的递归调用开始,一直到递归结束