使用递归的思想解题。
明确递归函数作用为得到一个已经反转的链表头结点。
最小子问题:将两个结点反转,将已经反转的链表看做一个结点。
特殊情况:遇到空链表或只有一个结点的返回其自身。
需要注意的是 在反转了以 head.next 为头结点的链表后,head 的 next 是指向该链表的最后一个元素的。因此可以利用这一点进行反转操作。head.next.next = head 。将链表最后一个元素的 next 指向 head ,再让head 指向null,完成反转。
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode res = ReverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
}