我的反转链表的递归方法有问题吗?因为我得到以下输出,在反转后仅打印 1 个:
原始链表: 1-->2-->3-->4-->5-->尾部
使用递归的反向链表: 1-->尾部
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);
关于java - 使用递归反转链表生成错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466192/