由浅入深:先看206题(简单)
参考大神的解析
https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/bu-bu-chai-jie-ru-he-di-gui-di-fan-zhuan-lian-biao/
写不出来如此简洁优秀的递归代码,那么就分析一下优美的代码吧!
public ListNode reverseList(ListNode head) {
if(head==null)
return null;
if (head.next == null) return head;//递归的终止条件
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
那么输入 reverse(head) 后,会在这里进行递归:
ListNode last = reverse(head.next);
不要跳进递归(你的脑袋能压几个栈呀?),而是要根据刚才的函数定义,来弄清楚这段代码会产生什么结果: