题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ function reverseBetween(head, m, n) { // write code here const myReverse = (head, tail) => { let prev = tail.next; let p = head; while (prev !== tail) { const nex = p.next; p.next = prev; prev = p; p = nex; } return [tail, head]; }; const dummy = new ListNode(0); dummy.next = head; let pre = dummy; let mpHead = head; let npTail = head; for (let i = 1; i < m; i++) { pre = pre.next; mpHead = mpHead.next } for (let i = 1; i < n; i++) { npTail = npTail.next } const nex = npTail.next; [mpHead, npTail] = myReverse(mpHead, npTail); pre.next = mpHead; npTail.next = nex; return dummy.next; } module.exports = { reverseBetween: reverseBetween, };