Wednesday, 31 October 2018

how to create doubly circular linked list in java


package hello;

public class MyLinkedList<E> {

private Node<E> first;
private Node<E> last;
int size;

public MyLinkedList() {
size = 0;
}

public int size() {
return size;
}

public static class Node<E> {
Node<E> next;
Node<E> pre;
E elelement;

public Node(Node p, E e, Node n) {
this.elelement = e;
this.next = n;
this.pre = p;
}

public E getElelement() {
return elelement;
}

public void setElelement(E elelement) {
this.elelement = elelement;
}

public Node<E> getNext() {
return next;
}

public void setNext(Node<E> next) {
this.next = next;
}

public Node<E> getPre() {
return pre;
}

public void setPre(Node<E> pre) {
this.pre = pre;
}

}

public void printForward() {
Node n = first;
for (int i = 0; i < size; i++) {
if (n.getPre() == null) {
System.out.print(n.getPre() + "::" + n.getElelement());
n = n.next;
} else if (n.getNext() == null) {
System.out.println("-->" + n.getElelement() + "::" + n.getNext());
} else {
System.out.print("-->" + n.getElelement() + "::");
n = n.next;
}

}

}

public void printBackward() {

System.out.println();
Node n = last;
for (int i = 0; i < size; i++) {
if (n.getNext() == null) {
System.out.print(n.getNext() + "-->::" + n.getElelement());
n = n.pre;
} else if (n.getPre() == null) {
System.out.println("-->" + n.getElelement() + "::-->" + n.getPre());
} else {
System.out.print("-->" + n.getElelement() + "::");
n = n.pre;
}

}

}

public void add(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
}
size++;
}

public void addCircular(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
newNode.next = first.pre;
first.pre = l.next;
}
size++;
}

public static void main(String[] args) {
MyLinkedList<Integer> iList = new MyLinkedList<Integer>();
iList.add(1);
iList.add(2);
iList.add(3);
iList.add(4);
iList.printForward();
iList.printBackward();
System.out.println("--------------------------------------------------------------");

iList.addCircular(1);
iList.addCircular(2);
iList.addCircular(3);
iList.addCircular(4);
iList.printForward();
// System.out.println(iList.size);
}

}