1
\$\begingroup\$

(The previous and the initial iteration.)

After some critique, I found the way to keep the rotation operation also for java.util.Lists 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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Input validation

If the list is empty, there will be division by zero. Since you check for null input list, it would make sense to do likewise for empty list as well.

Type parameter

The <T> is not needed in the Collections.<T>reverse statements, this works just fine:

Collections.reverse(list);
Collections.reverse(list.subList(0, rotationCount));
Collections.reverse(list.subList(rotationCount, list.size()));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.