题目:
https://leetcode-cn.com/problems/reverse-linked-list-ii/
我的写法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode successor=null;//存为后驱节点
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head==null){
return null;
}
if(left==1){
//反转前n个节点
resverN(head,right);
}
//反转以head.next起点的n-1个节点
head.next = reverseBetween(head.next,left-1,right-1);
//头结点为head
return head;
}
public ListNode resverN(ListNode head,int n){
//反转前n个节点
if(n==1){
//因为反转前n个节点,反转的节点不一定是null,我们需要记录其后驱节点
successor = head.next;
//头节点为第一个节点
return head;
}
//反转以head.next之后的n-1个节点,其头结点为last
ListNode last = resverN(head.next,n-1);
//链接第一个结点
head.next.next = head;
//反转部分和不需要反转的部分连接起来
head.next = successor;
//总体的头结点
return last;
}
}
执行结果:
然后想了两个小时,觉得挺对的思路,但是就是无法正确执行,然后找逻辑错误啊什么的。想不出来。
于是觉得今天学习太久了(大概12小时了,难受),然后洗洗睡了。第二天,看题解里面的,别人一样的思路(都是参考那本书的思维)
运行结果:
然后我就气啊,他都加非空判断都能过,我为什么过不了,于是发去问同学:
然后我可以原地裂开了。
如何做这道题呢,我是先看了别人的讲解:
https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/shou-ba-shou-shua-lian-biao-ti-mu-xun-lian-di-gui-si-wei/di-gui-fan-zhuan-lian-biao-de-yi-bu-fen