描述
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
题解
这道题的具体思路,可参看labuladong的 这篇文章
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} left
* @param {number} right
* @return {ListNode}
*/
var reverseBetween = function(head, left, right) {
if (left === 1) {
return reverseN(head, right);
}
head.next = reverseBetween(head.next, left - 1, right - 1);
return head;
};
let successor = null;
// 将链表的前 n 个节点反转(n <= 链表长度)
var reverseN = function (head, n) {
if (n === 1) {
successor = head.next; // 记录第 n+1 个节点
return head;
}
let result = reverseN(head.next, n - 1);
head.next.next = head;
head.next = successor;
return result;
};