Java 递归链表。我做错了什么?

Java 递归链表。我做错了什么?,java,recursion,linked-list,singly-linked-list,Java,Recursion,Linked List,Singly Linked List,这是我的密码。它没有打印任何东西 我认为由于递归,它指向空指针,因此在空位置不存在数据 请告诉我怎样才能使代码正确 提前感谢问题在于,您的反向调用在递归调用自身后,不会对头部做任何事情 基本情况是正确的:当head为null时,返回null。但是,递归步骤还没有完成:您需要反转列表的其余部分,但必须将其重新附加到头上 实现这一点的最简单方法是为previor节点传递一个额外的参数,以便 public class Reverse { public static void printLL(No

这是我的密码。它没有打印任何东西

我认为由于递归,它指向空指针,因此在空位置不存在数据

请告诉我怎样才能使代码正确


提前感谢

问题在于,您的
反向调用
在递归调用自身后,不会对
头部
做任何事情

基本情况是正确的:当
head
null
时,返回
null
。但是,递归步骤还没有完成:您需要反转列表的其余部分,但必须将其重新附加到
头上

实现这一点的最简单方法是为
previor
节点传递一个额外的参数,以便

public class Reverse {

  public static void printLL(Node head) {
      while(head!=null){
          System.out.print(head.getData()+"-->");
          head=head.next;
      }
  }

  public static Node reverseLL(Node head){
      if(head == null) {
          return head;
      }
      return reverseLL(head.next);
  }

  public static void main(String[] args) {
      Node first=new Node(10);
      Node head=first;
      Node second=new Node(20);
      first.next=second;
      Node third=new Node(30);
      second.next=third;
      Node fourth=new Node(40);
      third.next=fourth;
      printLL(head);
      System.out.println("\nReverse of Linked List is \n");
      head=reverseLL(head);
      printLL(head);
   }
}
在递归方法内部。下面是您的“包装器”方法的外观:

head.next = prior;
注意,它不是递归的——它所做的只是调用一个双参数重载

递归方法知道
head
永远不会
null
,因此它的基本情况是
head.next==null

public static Node reverseLL(Node head) {
    if(head==null){
        return null;
    }
    return reverseLL(head, null);
}
节点的反转在
返回
之前的赋值中完成。注意该方法如何返回链中最后一个非空节点


您的
反向调用
只需遍历所有节点,当它到达最后一个节点时,如果(head==null)
,则返回
null


您需要修复
reverseLL
功能。尝试向函数中添加跟踪,以逐步了解它的功能。

您似乎错过了递归的一个关键点—您必须调用自己

我将建议对
printl
进行更改,以演示一种可能的递归解决方案

public static Node reverseLL(Node head, Node prior) {
    Node res;
    if (head.next == null) {
        res = head;
    } else {
        res = reverseLL(head.next, head);
    }
    head.next = prior;
    return res;
}

请注意,代码基本上是如何表示如果有头,则打印它的数据,然后打印它的
头。下一步

是否有堆栈跟踪?我不知道堆栈跟踪。方法
reverseLL
应该如何反转链接列表?据我所见,它总是返回null。您必须实际构造一个新的链表(鉴于它是单向的),它才能工作。对
printLL
的第一个调用应该是打印一些东西。
reverseLL
之后的那一个不能工作。它可以工作……你能告诉我如何修改我的代码,以便通过printLL(head)函数打印反向链表吗?@iVvaibhav-如果你正在学习递归,让别人帮你做也无济于事。检查我编写的代码,找出发生在你身上的事情,然后修改你的反向过程,使之正确。
public static void printLL(Node head) {

    if (head != null) {
        System.out.print(head.getData() + "-->");
        printLL(head.next);
    }
}