我正在编写代码以使用递归来反转链表。我得到这个错误,不明白为什么?任何帮助将不胜感激。
/**
* 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;
}
}
答案 0 :(得分:0)
我通过创建代码段来运行代码:
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);
}
}
通过运行这个简单的测试,我假设代码正常工作。您必须可视化链接列表的工作方式,因为很可能您在链接列表中有循环,这就是您收到错误的原因。