Search for a command to run...
Connect tail to head, find the new split point, and cut the link to rotate the list in O(n)
Phase 1: Calculate Length
temp set to head node. Starting length count at 1.
Form Circular Loop
1class Solution {2 rotateRight(head, k) {3 if (!head || !head.next || k === 0) 4 return head;5 6 // Step 1: Calculate length7 let temp = head;8 let length = 1;9 while (temp.next) {10 length++;11 temp = temp.next;12 }13 14 // Step 2: Link tail to head15 temp.next = head;//temp: 1length: 116 17 // Handle k greater than length18 k = k % length; 19 20 // Step 3: Find new tail21 let end = length - k; 22 while (end-- > 1) 23 temp = temp.next;24 25 // Step 4: Break link26 head = temp.next;27 temp.next = null;28 29 return head;30 }31}