Problem
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
1 | |
Example 2:
1 | |
Explanation
-
We need two pointers, slow and fast. Fast pointer move k step ahead, then both slow and fast pointer move at the same time until fast pointer hits the end.
-
Now,
fast.next = head,head = slow.next, andslow.next = null. -
Corner case is when
kis bigger than the size of the linkedlist. Actually, the k isk = k % size.
Solution
1 | |