0
是不是有什麼毛病我扭轉了鏈表的遞歸方法?因爲我得到以下輸出只有1反轉後得到的印刷:使用遞歸扭轉鏈表產生錯誤的輸出
原始鏈表: 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";
}
}