There's more ...
package algo;
import java.util.NoSuchElementException;
public class CircularLinkedList<E> {
private Entry<E> head;
// Last element of the list. tail.next = head
private Entry<E> tail;
private int size = 0;
/**
* Class to hold the individual elements.
* @param <E>
*/
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;
}
/**
* Remove obj from the circular linked list and return the removed object
* @param obj
* @return
*/
public E remove(E obj) {
if (head == null || tail == null)
throw new NoSuchElementException();
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 NoSuchElementException(obj.toString());
}
E result = found.element;
temp.next = found.next;
found.next = null;
found.element = null;
size--;
return result;
}
/**
* Add obj to the circular linked list.
* @param obj
*/
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;
}
/**
* Size of the list.
* @return
*/
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"));
}
}
No comments:
Post a Comment