Is there a Java LinkedList method to use as a ring list?

Viewed 303

If I have a LinkedList:

Value A B C D E F
Index 0 1 2 3 4 5

I want to reorder the list or an Iterator for example at D(index 3) to be the new head but keep the order like:

Value D E F A B C
Index 0 1 2 3 4 5

Is this a functionality that can be achieved with LinkedList out of the box, basically realizing a ring? Is there another class that offers this already implemented?

3 Answers

You can use Collections.rotate for classes that implement the List interface:

List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F");
Collections.rotate(list, 3);
System.out.println(list);

Output:

[D, E, F, A, B, C]

No, this is not possible using any standard class in Java. You have to create you own implementation base on any ordered random access collection like: Array, List.

Following solution probably not optimal, but it works and was written in 5 minutes.

public static void main(String... args) throws IOException {
    Deque<Character> deque = new LinkedList<>();
    deque.addAll(Arrays.asList('A', 'B', 'C', 'D', 'E', 'F'));
    System.out.println(deque);
    reorder(deque, 3);
    System.out.println(deque);
    reorder(deque, 3);
}

public static void reorder(Deque<Character> deque, int offs) {
    offs %= deque.size();

    for (int i = 0; i < offs; i++)
        deque.add(deque.removeFirst());
}

Output:

[A, B, C, D, E, F]
[D, E, F, A, B, C]

P.S. As you can see the method accepted Deque, so you could use any implementation of this interface.

Here is a really simple way using List::subList(int fromIndex, int toIndex):

List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F");

int index = list.indexOf("D"); // or a fixed number, depends on your implementation

List<String> newList = new ArrayList<>();
newList.addAll(list.subList(index, list.size()));  // right part [D, E, F] first
newList.addAll(list.subList(0, index));            // left part [A, B, C] then

The newList will contain [D, E, F, A, B, C], however it doesn't use any advantage of the linked structures.

Related