簡體   English   中英

使用遞歸反轉鏈表產生錯誤的輸出

[英]reversing the linkedlist using recursion generating wrong output

我的反向鏈接列表的遞歸方法有什么問題嗎? 因為我得到以下輸出,反轉后僅輸出1:

原始鏈接列表: 1-> 2-> 3-> 4-> 5-> Tail

使用遞歸反向鏈接列表: 1-> Tail

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

您離工作代碼不太遠:

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

REPL


關鍵點:

  1. 您根本不需要currenthead是不變的。
  2. 您應該返回(並傳播)“ New Head”,從最深的遞歸調用一直到遞歸為止。

暫無
暫無

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

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