題目
描述
翻轉(zhuǎn)一個(gè)鏈表
樣例
給出一個(gè)鏈表1->2->3->null
芍殖,這個(gè)翻轉(zhuǎn)后的鏈表為3->2->1->null
解答
思路
遞歸疾嗅。從尾部反轉(zhuǎn)。
代碼
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
//如果頭指針為null或者只有頭指針冕象,直接返回
if(head == null || head.next == null){
return head;
}
ListNode reNode = reverse(head.next);
head.next.next = head;
head.next = null;
return reNode;
}
}