Rotating list
Given a linked list, move each node of the list k bits to the right.
The problem solving code
Find the end node of the linked list, string the list into a loop, and move k nodes in turn
var rotateRight = function(head, k) {
if(! head)return null;
let n = 1; // Record the length of the list
let p = head; // Record the header
while (p.next) {
p = p.next;
n += 1;
}
p.next = head; // join the top node to become a circular list
k %= n; // If k is large, it will loop a lot. This time directly with the drop list length.
k = n - k; // Subtract k from the final number of steps.
while (k--) p = p.next; // Move the k bit list
head = p.next; // After the move, assign the loop's linked list to the header
p.next = null; // Break the last node of the circular list, that is, the list after moving k bits
return head;
};
Copy the code