题解 | #链表内指定区间反转#
链表内指定区间反转
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 if (!head || !head.next || m === n) { return head; } let headKeep; let tailKeep; let between; let cur = head; let i = 1; while (cur && i <= n + 1) { let temp = cur; cur = cur.next; if (i < m) { if (!headKeep) { headKeep = temp; headKeep.next = null; } else { headKeep.next = temp; headKeep = headKeep.next; } } if (i >= m && i <= n) { if (!between) { between = temp; between.next = null; } else { temp.next = between; between = temp; } } if (i > n) { tailKeep = temp; } i++; } if (headKeep) { headKeep.next = between; } else { head = between; } if (tailKeep) { let btw = between; while (btw) { if (!btw.next) { btw.next = tailKeep; return head; } btw = btw.next; } } return head; } module.exports = { reverseBetween: reverseBetween, };
结题思路:把链表拆分成3部分,头部不变序段,中间m-n反转段以及末尾段,中间反转,然后首中尾相连,重新组合
#链表调整顺序#