import java.util.Iterator;
public class CircularLinkedList<E> implements Iterable<E> {
private Node<E> head;
private int size;
private static class Node<E> {
E data;
Node<E> next;
Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
}
public CircularLinkedList() {
head = null;
size = 0;
}
public void insert(E element) {
if (head == null) {
head = new Node<>(element, null);
head.next = head;
} else {
Node<E> newNode = new Node<>(element, head.next);
head.next = newNode;
}
size++;
}
public void delete(E element) {
if (head == null) {
return;
}
if (head.data.equals(element)) {
if (size == 1) {
head = null;
} else {
Node<E> current = head;
while (!current.next.data.equals(element)) {
current = current.next;
}
current.next = current.next.next;
if (element.equals(head.data)) {
head = current.next;
}
}
size--;
} else {
Node<E> current = head;
while (!current.next.data.equals(element)) {
current = current.next;
if (current.next == head) {
return;
}
}
current.next = current.next.next;
size--;
}
}
public Node<E> find(E element) {
Node<E> current = head;
if (head != null) {
do {
if (current.data.equals(element)) {
return current;
}
current = current.next;
} while (current != head);
}
return null;
}
public void modify(int index, E element) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
Node<E> current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
current.data = element;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private Node<E> current = head;
private int count = 0;
@Override
public boolean hasNext() {
return count < size;
}
@Override
public E next() {
E data = current.data;
current = current.next;
count++;
return data;
}
};
}
}