The answer of the linked question is easily expandable to an arbitrary number of objects, if you have a way to specify the needed nodes at construction time, e.g.
final class CircularLinkedList<T> {
final CircularLinkedList<T> next;
final T value;
public CircularLinkedList(T firstValue, List<T> other) {
value = firstValue;
next = other.isEmpty()? this: new CircularLinkedList<>(this, 0, other);
}
private CircularLinkedList(CircularLinkedList<T> head, int pos, List<T> values) {
value = values.get(pos);
next = ++pos == values.size()? head: new CircularLinkedList<>(head, pos, values);
}
@Override
public String toString() {
StringJoiner sj = new StringJoiner(", ").add(value.toString());
for(CircularLinkedList<T> node = next; node != this; node = node.next)
sj.add(node.value.toString());
return sj.toString();
}
}
Which you can use like
CircularLinkedList<String> cll
= new CircularLinkedList<>("first", Arrays.asList("second", "third", "fourth"));
System.out.println(cll);
// demonstrate the wrap-around:
for(int i = 0; i < 10; i++, cll = cll.next) {
System.out.print(cll.value+" .. ");
}
System.out.println(cll.value);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…