给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
reverseN方法为返回翻转前N个结点的链表的头节点;
/**
* 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 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;
}
public ListNode successor;
public ListNode reverseN(ListNode head,int n){
if(n == 1){
successor = head.next;
return head;
}
ListNode temp = reverseN(head.next,n-1);
head.next.next = head;
head.next = successor;
return temp;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:39 MB, 在所有 Java 提交中击败了64.25%的用户
通过测试用例:44 / 44