我的扭转链表的递归方法有问题吗?因为我得到以下输出,只有1个在反转后打印:
原始LinkedList: 1 - →2 - →3 - →4 - →5 - >尾
使用递归反转LinkedList: 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";
}
}
答案 0 :(得分:2)
在ReverseRecursion
中,
您永远不会将反向列表分配回head
。
改变这一行:
ReverseRecursion(current.next);
对此:
head = ReverseRecursion(current.next);
答案 1 :(得分:1)
您距离工作代码不远:
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
关键点:
current
,head
是不可变的。