簡體   English   中英

遞歸-鏈表反轉期間線程“ main”中的異常java.lang.StackOverflowError

[英]Recursion - Exception in thread “main” java.lang.StackOverflowError during linked-list reversal

我正在編寫代碼以使用遞歸來反向鏈接列表。 我收到此錯誤,不明白為什么? 任何援助將不勝感激。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     public int val;
 *     public ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */

public class Solution{
    public ListNode reverseList(ListNode a){
        if(a==null || a.next==null)return a;       
        ListNode ans=null;
        ans = reverse(a,ans);
        return ans;
    }
    private ListNode reverse(ListNode aa, ListNode ans){
        if(aa.next==null){
            ans = aa;
            return ans;
        }
        ans = reverse(aa.next, ans);
        ListNode temp = aa.next;
        temp.next=aa;
        aa.next=null;
        return ans;
    }
}

我已經通過創建代碼段來運行您的代碼:

public class Solution {

    public static ListNode reverseList(ListNode a){
        if(a==null || a.next==null)return a;
        ListNode ans=null;
        ans = reverse(a,ans);
        return ans;
    }

    private static ListNode reverse(ListNode aa, ListNode ans){
        if(aa.next==null){
            ans = aa;
            return ans;
        }
        ans = reverse(aa.next, ans);
        ListNode temp = aa.next;
        temp.next=aa;
        aa.next=null;
        return ans;
    }

    public static class ListNode {
        public int data;       // data stored in this node
        public ListNode next;  // link to next node in the list

        // post: constructs a node with data 0 and null link
        public ListNode() {
            this(0, null);
        }

        // post: constructs a node with given data and null link
        public ListNode(int data) {
            this(data, null);
        }

        // post: constructs a node with given data and given link
        public ListNode(int data, ListNode next) {
            this.data = data;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode last = new ListNode(3);
        ListNode middle = new ListNode(2, last);
        ListNode first = new ListNode(1, middle);

        ListNode listNode = reverseList(first);

        System.out.println(listNode.data);
        System.out.println(listNode.next.data);
        System.out.println(listNode.next.next.data);

    }

}

通過運行此簡單測試,我假設代碼可以正常工作。 您必須可視化鏈表的工作方式,因為很可能您已在鏈表中循環,這就是為什么會出錯的原因。

暫無
暫無

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

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