Fix Circular linked list (#2598)

This commit is contained in:
DEBADRIBASAK 2021-10-16 19:01:24 +05:30 committed by GitHub
parent b6dc9617f6
commit 60a0c23544
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -15,12 +15,14 @@ public class CircleLinkedList<E> {
private int size;
// this will point to dummy node;
private Node<E> head = null;
private Node<E> 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<E>(null, head);
tail = head;
size = 0;
}
@ -37,10 +39,43 @@ public class CircleLinkedList<E> {
throw new NullPointerException("Cannot add null element to the list");
}
// head.next points to the last element;
head.next = new Node<E>(value, head);
if (tail == null){
tail = new Node<E>(value, head);
head.next = tail;
}
else{
tail.next = new Node<E>(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<Integer>();
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<E> {
// 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;