要求很簡單,輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭
遞歸的大致過程,就是從鏈表最後一個結點開始,依次回溯到head頭結點,實現翻轉
大致步驟如下
首先第一步,創建一個結點類
class Node{
public int id;
public Node next;
public Node(int id){
this.id=id;
}
}
然後開始編寫反轉方法,此處以 head->1->2 鏈表舉例
public Node reverse(Node head){
/*
LinkedList: head->1->2
1> 第一層遞歸
temp=head.next (temp=1)
newHead=reverse(1)
2> 第二層遞歸
temp=head.next (temp=2)
newHead=reverse(2) 返回2
2.next=head (1) 後面的結點的next等於前面的結點
head.next=null 刪除前面結點的指向
return newHead (2)
3> 回到第一層遞歸
newHead=2
1.next=head 後面的結點的next等於前面的結點
head.next=null 刪除前面結點的指向
return newHead 此時的newHead爲新的頭結點
*/
if (head==null || head.next==null){
return head;
}
Node temp=head.next;
Node newHead=reverse(head.next);
temp.next=head;
head.next=null;
return newHead;
}