From 60a0c23544a049bb9dee002ceeaabee578f60a5a Mon Sep 17 00:00:00 2001 From: DEBADRIBASAK <32904247+DEBADRIBASAK@users.noreply.github.com> Date: Sat, 16 Oct 2021 19:01:24 +0530 Subject: [PATCH] Fix Circular linked list (#2598) --- DataStructures/Lists/CircleLinkedList.java | 40 +++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/DataStructures/Lists/CircleLinkedList.java b/DataStructures/Lists/CircleLinkedList.java index b1f9ec77..de264ddc 100644 --- a/DataStructures/Lists/CircleLinkedList.java +++ b/DataStructures/Lists/CircleLinkedList.java @@ -15,12 +15,14 @@ public class CircleLinkedList { private int size; // this will point to dummy node; private Node head = null; + private Node tail = null; // keeping a tail pointer to keep track of the end of list // constructer for class.. here we will make a dummy node for circly linked list implementation // with reduced error catching as our list will never be empty; public CircleLinkedList() { // creation of the dummy node head = new Node(null, head); + tail = head; size = 0; } @@ -37,10 +39,43 @@ public class CircleLinkedList { throw new NullPointerException("Cannot add null element to the list"); } // head.next points to the last element; - head.next = new Node(value, head); + if (tail == null){ + tail = new Node(value, head); + head.next = tail; + } + else{ + tail.next = new Node(value, head); + tail = tail.next; + } size++; } + // utility function for teraversing the list + public String toString(){ + Node p = head.next; + String s = "[ "; + while(p!=head){ + s += p.value; + s += " , "; + p = p.next; + } + return s + " ]"; + } + + public static void main(String args[]){ + CircleLinkedList cl = new CircleLinkedList(); + cl.append(12); + System.out.println(cl); + cl.append(23); + System.out.println(cl); + cl.append(34); + System.out.println(cl); + cl.append(56); + System.out.println(cl); + cl.remove(3); + System.out.println(cl); + } + public E remove(int pos) { if (pos > size || pos < 0) { // catching errors @@ -58,6 +93,9 @@ public class CircleLinkedList { // the last element will be assigned to the head. before.next = before.next.next; // scrubbing + if(destroy == tail){ + tail = before; + } destroy = null; size--; return saved;