(java)反转单链表的递归实现
1)递归思想
递归思想类似于数学归纳法的应用,先定义一个 某个功能的方法(先想好功能,再单位的代码实现) ,然后在代码实现中调用,其中结束条件是关键(需要想清楚栈的工作原理)。
2)上代码
public class Solution {
public static void main(String[] args) {
ListNode head = createList(11);
printList(head);
System.out.println();
head = reverseList(head);
printList(head);
}
//返回一个已经反转的链表的头指针
public static ListNode reverseList(ListNode head) {
//当传入一个节点,调用可以 返回反转链表头指针的函数 (就像数学归纳法),来将head连接在这个链表的尾部,然后返回头指针
//递归的结束条件就是当传入的是空指针或者传入的head的下一个是空指针,就返回一个这个指针
//递归结束条件
if (head == null || head.next == null) {
return head;
}
//调用递归
ListNode node = reverseList(head.next);
//对单个节点进行操作
ListNode newHead = node;
while (node.next != null) {
node = node.next;
}
node.next = head;
head.next = null;
//返回头节点(也就是这个方法的功能)
return newHead;
}
public static ListNode createList(int n) {
ListNode head = new ListNode(1);
ListNode x = head;
for (int i = 1; i < n; i++) {
x.next = new ListNode(i + 1);
x = x.next;
}
return head;
}
public static void printList(ListNode head) {
while (head != null) {
System.out.printf("%5d", head.val);
head = head.next;
}
}
}