import java.util.Iterator;
public class CircularLinkedList<E> implements Iterable<E> {
private Node<E> head;
private int size;
private static class Node<E> {
private E data;
private Node<E> next;
public Node(E data) {
this.data = data;
}
}
public CircularLinkedList() {
head = null;
size = 0;
}
public void insert(E data) {
Node<E> newNode = new Node<>(data);
if (head == null) {
head = newNode;
head.next = head;
} else {
Node<E> temp = head;
while (temp.next != head) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = head;
}
size++;
}
public void delete(E data) {
if (head != null) {
if (head.data.equals(data)) {
if (head.next == head) {
head = null;
} else {
Node<E> temp = head;
while (temp.next != head) {
temp = temp.next;
}
temp.next = head.next;
head = head.next;
}
size--;
} else {
Node<E> current = head;
Node<E> previous = null;
do {
if (current.data.equals(data)) {
previous.next = current.next;
size--;
break;
}
previous = current;
current = current.next;
} while (current != head);
}
}
}
public boolean contains(E data) {
if (head == null) {
return false;
} else {
Node<E> temp = head;
do {
if (temp.data.equals(data)) {
return true;
}
temp = temp.next;
} while (temp != head);
return false;
}
}
public void modify(int index, E data) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
Node<E> temp = head;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
temp.data = data;
}
@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;
}
};
}
}