Given the head
of a linked list, rotate the list to the right by k
places.
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4 Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500]
. -100 <= Node.val <= 100
0 <= k <= 2 * 109
class Solution: def rotateRight(self, head, k): length = 0 ptr = head if head == None or head.next == None: return head while ptr!= None: length = length+1 ptr = ptr.next res = k%length ptr = head if res == 0: return head for _ in range(length-res-1): ptr = ptr.next newhead = ptr.next ptr.next = None temp = newhead while temp.next!=None: temp = temp.next temp.next = head return newhead