剑指 Offer 24. 反转链表


题目:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

public class demo_1115_24 {


    /**
     * 思路: 递归,到最后每一层都是两个步骤
     *       1. 递归返回的节点(即后置节点)指向当前节点(即前置节点),
     *       2. 斩断 当前节点的next , 所以每一层的递归 都会有:前置节点被两边夹击
     */
    class Solution {
        ListNode listNode = new ListNode();

        public ListNode reverseList(ListNode head) {
            if (head == null) return null;
            res(head);
            return listNode;
        }

        //[1,2,3,4,5]
        private ListNode res(ListNode head) {
            if (head.next == null) {
                listNode = head;
                return head;
            }
            ListNode node = res(head.next);
            node.next = head;
            head.next = null;
            return head;

        }
    }
}