/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode}head * @param {number}k * @return {ListNode} */ var rotateRight = function(head, k) { if (!head || !head.next) return head
// 先闭合环 var old_tail = head var n = 1 while (old_tail.next) { old_tail = old_tail.next n++ } old_tail.next = head
// 断开 var new_tail = head var new_head = head for (var i = 0; i < n - k % n - 1; i++) { new_tail = new_tail.next } new_head = new_tail.next // 重新计算新的头结点 new_tail.next = null// 断开