Skip to content

Instantly share code, notes, and snippets.

@biskandar
Created October 20, 2016 22:30
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/5018c1f283bb0f78d3787ac7970943e0 to your computer and use it in GitHub Desktop.
Save biskandar/5018c1f283bb0f78d3787ac7970943e0 to your computer and use it in GitHub Desktop.
Java: Circular Linked List
package com.careercup.linkedlist;
public class CircularLinkedList {
public static class Node<AnyType> {
private AnyType data;
private Node<AnyType> next;
public Node( AnyType data ) {
this.data = data;
}
public AnyType getData() {
return data;
}
public Node<AnyType> getNext() {
return next;
}
public void setNext( Node<AnyType> next ) {
this.next = next;
}
}
public static Node<Integer> createLinkedList( Integer... numbers ) {
Node<Integer> nodeTop = null;
if ((numbers == null) || (numbers.length < 1)) {
return nodeTop;
}
Node<Integer> nodeBottom = null , nodeCurr = null;
for (int idx = 0; idx < numbers.length; idx++) {
nodeCurr = new Node<Integer>(numbers[idx]);
if (nodeTop == null) {
nodeTop = nodeCurr;
} else {
nodeBottom.setNext(nodeCurr);
}
nodeBottom = nodeCurr;
nodeBottom.setNext(nodeTop);
}
// Top Bottom
// v v
// 1 -> 2 -> 3 -> 4
// ^ |
// |______________|
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();
}
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