Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion DataStructures/Lists/CircleLinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ private Node(E value, Node<E> next) {
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;
}

Expand All @@ -37,10 +39,43 @@ public void append(E value) {
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
Expand All @@ -58,6 +93,9 @@ public E remove(int pos) {
// 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;
Expand Down