LeetCode #61 Rotate List
Problem
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
Solution
Use two pointers runner
and walker
. Let runner
runs entire list to calculate amount of nodes, say n
, in list and stop at the last node. Then k % n = l
for reducing unneeded move. At last, move walker
to position n-l
, which takes n-l-1
steps, and attach tail of list to head and reassign new head.
Complexity
runner
running entire list takes O(n) time if n
denotes to amount of nodes in this list. Then walker
will take O(l) time. Because l = k % n
, we know l
will be less than n
. Therefore, total time complexity is O(n+l) = O(n).
It’s trivial that it only takes O(1) extra space.