Skip to content

Instantly share code, notes, and snippets.

@biskandar
Created October 20, 2016 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biskandar/a1f6c4be61717126789e82f159298e37 to your computer and use it in GitHub Desktop.
Save biskandar/a1f6c4be61717126789e82f159298e37 to your computer and use it in GitHub Desktop.
Java: Circular Double Linked List
package com.careercup.linkedlist;
public class CircularDoubleLinkedList {
public static class Node<AnyType> {
private AnyType data;
private Node<AnyType> next;
private Node<AnyType> prev;
public Node( AnyType data ) {
this.data = data;
}
public Node<AnyType> getNext() {
return next;
}
public void setNext( Node<AnyType> next ) {
this.next = next;
}
public Node<AnyType> getPrev() {
return prev;
}
public void setPrev( Node<AnyType> prev ) {
this.prev = prev;
}
public AnyType getData() {
return data;
}
}
public static Node<Integer> createLinkedList( Integer... numbers ) {
Node<Integer> nodeTop = null;
if ((numbers == null) || (numbers.length < 1)) {
return nodeTop;
}
Node<Integer> nodeBottom = null;
for (int idx = 0; idx < numbers.length; idx++) {
Node<Integer> nodeNew = new Node<Integer>(numbers[idx]);
if (nodeTop == null) {
nodeTop = nodeNew;
} else {
nodeBottom.setNext(nodeNew);
nodeNew.setPrev(nodeBottom);
}
nodeBottom = nodeNew;
nodeBottom.setNext(nodeTop);
nodeTop.setPrev(nodeBottom);
}
return nodeTop;
}
public static void print( Node node , int times ) {
if (node == null) {
return;
}
for (int idx = 0; idx < times; idx++) {
System.out.printf("%d ", node.getData());
node = node.getNext();
}
System.out.println();
for (int idx = 0; idx < times; idx++) {
System.out.printf("%d ", node.getData());
node = node.getPrev();
}
System.out.println();
}
public static void main( String[] args ) {
Node<Integer> node = createLinkedList(1, 2, 3, 4);
print(node, 8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment