反转链表 II
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表
链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| function reverseBetween( head: ListNode | null, left: number, right: number ): ListNode | null { if (left === 1) { return reverse(head, right) } head.next = reverseBetween(head.next, left - 1, right - 1) return head } const reverse = (function () { let back = null return function (head: ListNode, right: number): ListNode { if (right === 1) { back = head.next return head } const last: ListNode = reverse(head.next, right - 1) head.next.next = head head.next = back return last } })()
|