public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
在递归函数 reverseList 中,首先检查链表是否为空或只有一个节点。如果是,则直接返回原始链表。否则,使用递归函数 reverseList 反转除头节点之外的其余节点,并将其返回。接下来,将头节点的下一个节点的 next 指针设置为头节点,然后将头节点的 next 指针设置为 null,以将链表反转。最后,返回新的头节点。