92. 反转链表 II
给你单链表的头指针 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]
提示:
- 链表中节点数目为
n 1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
代码实现:
/*
* @lc app=leetcode.cn id=92 lang=javascript
*
* [92] 反转链表 II
*/
// @lc code=start
/**
* 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 (!head) return null;
let ret = new ListNode(-1, head), pre = ret, cnt = right - left + 1;
while (--left) {
pre = pre.next;
}
pre.next = reverse(pre.next, cnt);
return ret.next;
};
var reverse = function (head, n) {
let pre = null, cur = head;
while (n--) {
[cur.next, pre, cur] = [pre, cur, cur.next];
}
head.next = cur;
return pre;
}
// @lc code=end