
write a program to create a circular linked list in java and perform operations on it?

import java.util.*;
public class CircularLinkedList<E> {
private Entry<E> head;
private Entry<E> tail;
private int size = 0;
private static class Entry<E> {
E element;
Entry<E> next;
Entry(E element, Entry<E> next) {
this.element = element;
this.next = next;
}
Entry(E element) {
this.element = element;
}
}
public CircularLinkedList() {
head = null;
}
public E remove(E obj) {
if (head == null || tail == null)
throw new Exception();
Entry<E> current = head, temp = head, found = null;
if (obj.equals(head.element)) {
if (head.next == head) {
found = head;
head = null;
tail = null;
size--;
return found.element;
} else {
found = head;
temp = tail;
}
} else {
current = head.next;
while (current != head) {
if (current.element.equals(obj)) {
found = current;
break;
}
temp = current;
current = current.next;
}
}
if (found == null) {
throw new Exception(obj.toString());
}
E result = found.element;
temp.next = found.next;
found.next = null;
found.element = null;
size--;
return result;
}
public void add(E obj) {
Entry e = new Entry(obj);
if (head == null) {
size++;
head = e;
head.next = head;
tail = head;
return;
}
size++;
e.next = head;
head = e;
tail.next = head;
}
public int size() {
return size;
}
public static void main(String[] args) {
CircularLinkedList<String> list = new CircularLinkedList<String>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
System.out.println(list.remove("Three"));
System.out.println(list.remove("Two"));
System.out.println(list.remove("One"));
System.out.println(list.remove("Four"));
System.out.println(list.remove("Four"));
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.