92.反转链表(反转指定区间的链表节点)
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
-
思路:第一步,实现反转前n个节点的链表;第二步,实现反转left和right区间节点的链表;当left为1时,则为实现反转前n个节点的链表;当left不为1时,则头节点指向下一节点、left的数量-1和right的数量-1;即同步前进(left-1)步,至left==1;递归第一步。
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if(left == 1){
return reverseN(head,right);
}
head.next = reverseBetween(head.next,left-1,right-1);
return head;
}
ListNode successor = null;
//实现反转前n个节点
public ListNode reverseN(ListNode head,int n){
if(n==1){
successor = head.next;
return head;
}
//新链表的头节点
ListNode last = reverseN(head.next,n-1);
head.next.next = head;
head.next = successor;
return last;
}
}
本文介绍了一种反转链表中指定区间节点的方法。通过递归方式实现了反转从位置left到位置right的链表节点,适用于单链表。文章详细阐述了反转前n个节点的链表及反转指定区间节点的具体步骤。
902

被折叠的 条评论
为什么被折叠?



