题解 | #调整牛群顺序#
调整牛群顺序
https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
function moveNthToEnd(head, n) {
// write code here
if(n === 1) return head;
const dummy = new ListNode(-1);
dummy.next = head;
let fast = dummy;
let slow = head;
// 要移动节点的前一个节点, 特殊情况:移动第一个节点
let movePreNode = dummy;
for(let i = 0; i < n; i++) {
fast = fast.next;
}
while(fast !== null && fast.next !== null) {
fast = fast.next;
if(fast.next === null) {
movePreNode = slow;
}
slow = slow.next;
}
// 此时, slow 是要移动的节点, fast 是最后一个节点
movePreNode.next = slow.next;
fast.next = slow;
slow.next = null;
return dummy.next;
}
module.exports = {
moveNthToEnd: moveNthToEnd,
};

