簡體   English   中英

遞歸鏈表。 我究竟做錯了什么?

[英]Recursive Linked List. What am I doing wrong?

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);
   }
}

這是我的代碼。 它沒有打印任何內容。

我認為由於遞歸,它指向空指針,因此在空位置上沒有數據。

請告訴我該怎么做才能使代碼正確。

提前致謝

您的reverseLL僅遍歷所有節點,當到達最后一個節點時執行if(head==null) ,則返回null

您需要修復reverseLL功能。 嘗試將跟蹤添加到函數中以逐步了解它的作用。

您似乎錯過了有關遞歸的關鍵點-您必須自稱。

我將建議對printLL進行更改,以證明一種可行的遞歸解決方案。

public static void printLL(Node head) {

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

請注意,代碼基本上怎么說的, 如果有頭,先打印數據,然后再打印head.next

問題是您的reverseLL在遞歸調用自己之后沒有對head做任何事情。

基本情況是正確的: headnull ,返回null 但是,遞歸步驟尚未完成:您需要反轉列表的其余部分,但隨后必須將其附加到head

完成此操作的最簡單方法是為prior節點傳遞一個額外的參數,以便您可以

head.next = prior;

在您的遞歸方法中。 這是您的“包裝器”方法的外觀:

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

請注意,它不是遞歸的-它所做的只是調用兩個參數的重載。

遞歸方法知道head永遠不會為null ,因此其基本情況為head.next == null

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;
}

head節點的反轉在return之前的分配中完成。 請注意,該方法如何返回鏈中的最后一個非空節點。

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM