开始系统的刷leetcode了,加油加油!
一、题目
题目:92. 反转链表 II
难度:中等
地址:https://leetcode-cn.com/problems/reverse-linked-list-ii/
使用语言:Java
二、代码
/**
* Created by Zhao Wen on 2021/2/4
* 92 反转链表
*/
public class _92 {
// 下一个结点存放
ListNode nextNode = null;
public ListNode reverseN(ListNode head, int n){
// 反转区间为 1~1
if(n == 1){
// 建立被反转结点与其后结点的联结
nextNode = head.next;
return head;
}
// 反转区间为1~n 递归调用函数继续反转
ListNode last = reverseN(head.next,n-1);
head.next.next = head;
// 让反转之后的head节点与后面的节点建立连接
head.next = nextNode;
return last;
}
public ListNode reverseBetween(ListNode head, int m, int n) {
// 从1开始,反转区间为1~n
if(m == 1){
return reverseN(head,n);
}
// 非1开始,反转区间为m~n
head.next = reverseBetween(head.next,m-1,n-1);
return head;
}
}
// 链表
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
ListNode(int val,ListNode next){
this.val = val;
this.next = next;
}
}
三、细节注意
1.递归的递归
此处分别使用了两个方法,实现了两个不同条件的递归:
对区间m~n之间的数值进行递归处理
public ListNode reverseBetween(ListNode head, int m, int n)
对前n个数的递归
reverseN(ListNode head, int n)
2.语言的特性
Java对象在方法中作为参数时都是值传递,而非引用传递,所以在通过递归改变对象时,一定要关注是否有改变到其对象真实引用,例如本题中的:
ListNode nextNode = null;
如果将上面这个对象声明放在reverseN中,在递归过程中一定会为空,进而影响后续结果
head.next = nextNode;