(The previous and the initial iteration.)
After some critique, I found the way to keep the rotation operation also for java.util.List
s that do not provide random access iterators:
package net.coderodde.util;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
/**
* This class contains a static method for rotating lists in linear time and
* constant space.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Oct 6, 2017)
*/
public final class ListRotation {
private ListRotation() {}
/**
* Performs the list rotation.
*
* @param <T> the list element type.
* @param list the list whose content to rotate.
* @param rotationCount the number of steps to rotate to the right. If
* negative, rotates to the left.
*/
public static <T> void rotate(List<T> list, int rotationCount) {
Objects.requireNonNull(list, "The input list is null.");
rotationCount %= list.size();
if (rotationCount < 0) {
rotationCount += list.size();
}
Collections.<T>reverse(list);
Collections.<T>reverse(list.subList(0, rotationCount));
Collections.<T>reverse(list.subList(rotationCount, list.size()));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list =
new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println(list);
while (true) {
int rotationCount = scanner.nextInt();
rotate(list, rotationCount);
System.out.println(list);
}
}
}
So how does that look now?