@@ -15,12 +15,14 @@ private Node(E value, Node<E> next) {
1515 private int size ;
1616 // this will point to dummy node;
1717 private Node <E > head = null ;
18+ private Node <E > tail = null ; // keeping a tail pointer to keep track of the end of list
1819
1920 // constructer for class.. here we will make a dummy node for circly linked list implementation
2021 // with reduced error catching as our list will never be empty;
2122 public CircleLinkedList () {
2223 // creation of the dummy node
2324 head = new Node <E >(null , head );
25+ tail = head ;
2426 size = 0 ;
2527 }
2628
@@ -37,10 +39,43 @@ public void append(E value) {
3739 throw new NullPointerException ("Cannot add null element to the list" );
3840 }
3941 // head.next points to the last element;
40- head .next = new Node <E >(value , head );
42+ if (tail == null ){
43+ tail = new Node <E >(value , head );
44+ head .next = tail ;
45+ }
46+ else {
47+ tail .next = new Node <E >(value , head );
48+ tail = tail .next ;
49+ }
4150 size ++;
4251 }
4352
53+ // utility function for teraversing the list
54+ public String toString (){
55+ Node p = head .next ;
56+ String s = "[ " ;
57+ while (p !=head ){
58+ s += p .value ;
59+ s += " , " ;
60+ p = p .next ;
61+ }
62+ return s + " ]" ;
63+ }
64+
65+ public static void main (String args []){
66+ CircleLinkedList cl = new CircleLinkedList <Integer >();
67+ cl .append (12 );
68+ System .out .println (cl );
69+ cl .append (23 );
70+ System .out .println (cl );
71+ cl .append (34 );
72+ System .out .println (cl );
73+ cl .append (56 );
74+ System .out .println (cl );
75+ cl .remove (3 );
76+ System .out .println (cl );
77+ }
78+
4479 public E remove (int pos ) {
4580 if (pos > size || pos < 0 ) {
4681 // catching errors
@@ -58,6 +93,9 @@ public E remove(int pos) {
5893 // the last element will be assigned to the head.
5994 before .next = before .next .next ;
6095 // scrubbing
96+ if (destroy == tail ){
97+ tail = before ;
98+ }
6199 destroy = null ;
62100 size --;
63101 return saved ;
0 commit comments