class CircularLinkedList { private Node first; private Node last; private int size; public CircularLinkedList() { first = last = null; size=0; } public void add(String value){ Node current = new Node(null, null, value); if(first == null){ first = current; current.setNext(first); current.setPrev(first); last = first; }else { last.setNext(current); current.setPrev(last); last = current; last.setNext(first); first.setPrev(last); } size++; } public void traverseRight(){ System.out.print("Traversing right: "); Node current = first; do{ System.out.print(current.value+" "); current = current.next; }while(current != first); System.out.println(""); } public void traverseLeft(){ System.out.print("Traversing left: "); Node current = first; do{ System.out.print(current.value+" "); current = current.prev; }while(current != first); System.out.println(""); } public void traverseLeft(int count){ System.out.print("Traversing left "+count+": "); Node current = first; do{ System.out.print(current.value+" "); current = current.prev; }while(count-- > 0); System.out.println(""); } public int getSize(){ return size; } static class Node { private String value; private Node next; private Node prev; public Node(Node next, Node prev, String value){ this.next = next; this.value = value; this.prev = prev; } public void setNext(Node next) { this.next = next; } public void setPrev(Node prev) { this.prev = prev; } } } public class CircularList { public static void main(String a[]) { CircularLinkedList linkedList = new CircularLinkedList(); linkedList.add("1"); linkedList.add("2"); linkedList.add("3"); linkedList.add("4"); linkedList.add("5"); linkedList.add("6"); linkedList.add("7"); linkedList.traverseRight(); linkedList.traverseLeft(); linkedList.traverseLeft(3); System.out.println("List size: " +linkedList.getSize()); } }
Tuesday 12 April 2016
Creating own circular list in java
Subscribe to:
Posts (Atom)