题解 | #旋转链表#
旋转链表
https://www.nowcoder.com/practice/1ad00d19a5fa4b8dae65610af8bdb0ed
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ function rotateLinkedList(head, k) { if (!head || k === 0) { return head; } // 计算链表长度 let length = 1; let current = head; while (current.next) { current = current.next; length += 1; } // 将链表变成循环链表 current.next = head; // 计算实际需要移动的步数 k = k % length; if (k === 0) { current.next = null; return head; } // 找到新的尾节点 let newTail = head; for (let i = 0; i < length - k - 1; i++) { newTail = newTail.next; } // 找到新的头节点 const newHead = newTail.next; // 断开循环链表 newTail.next = null; return newHead; } module.exports = { rotateLinkedList: rotateLinkedList, };