public class CycleLinkedListZH<E> {
public static final int ELEMENT_NOT_FOUND = -1;
private int size;
private CycleLinkedListZH.Node<E> headNode;
private static class Node<E> {
E element;
CycleLinkedListZH.Node<E> next = null;
public Node(E element, CycleLinkedListZH.Node<E> next) {
this.element = element;
this.next = next;
}
public Node() {
}
}
public void clear(){
headNode = null;
size = 0;
}
public int getSize(){
return size;
}
public void isEmptyPrint(){
if (headNode == null){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
}
public E getElement(int index){
CycleLinkedListZH.Node<E> node = indexSearchNode(index);
return node.element;
}
public void containsPrint(E element){
CycleLinkedListZH.Node<E> node = headNode;
for(int i = 0;i < size ; i++){
if (node.element == element){
System.out.println("Contain");
return;
}
node = node.next;
}
System.out.println("Not Contain");
}
public void add(int index , E element){
CycleLinkedListZH.Node<E> node = new Node<>();
node.element = element;
if (size == 0){
headNode = node;
node.next = node;
}else if (index == 0){
CycleLinkedListZH.Node<E> lastnode = indexSearchNode(size - 1);
lastnode.next = node;
node.next = headNode;
headNode = node;
}else{
CycleLinkedListZH.Node<E> nodePre = indexSearchNode(index-1);
node.next = nodePre.next.next;
nodePre.next = node;
}
size++;
}
public void remove(int index){
if (index == 0){
CycleLinkedListZH.Node<E> lastNode = indexSearchNode(size - 1);
lastNode.next = lastNode.next.next;
headNode = headNode.next;
}else if (size == 0||size == 1){
headNode = null;
} else{
CycleLinkedListZH.Node<E> nodePre = indexSearchNode(index-1);
nodePre.next = nodePre.next.next;
}
size--;
}
public void add(E element){
add(size,element);
}
private CycleLinkedListZH.Node<E> indexSearchNode (int index){
CycleLinkedListZH.Node<E> node = headNode;
for (int i = 0; i<index; i++){
node = node.next;
}
return node;
}
public String toString() {
StringBuilder string = new StringBuilder();
string.append("size=").append(size).append(" [");
CycleLinkedListZH.Node<E> node = headNode;
for (int i = 0; i < size; i++) {
if (i != 0) {
string.append(", ");
}
string.append(node.element);
node = node.next;
}
string.append("]");
return string.toString();
}
}