Skip to content

Commit e0b9205

Browse files
author
Moro-Code
committed
CircleLinkedList
Uses a dummy node and generics…. this implementation of a singly linked list eliminates need to use tail reference
1 parent 5105464 commit e0b9205

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

data_structures/CircleLinkedList.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class CircleLinkedList<E>{
2+
private static class Node<E>{
3+
Node<E> next;
4+
E value;
5+
private Node(E value, Node<E> next){
6+
this.value = value;
7+
this.next = next;
8+
}
9+
}
10+
private int size; //For better O.O design this should be private allows for better black box design
11+
private Node<E> head; //this will point to dummy node;
12+
public CircleLinkedList(){ //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;
13+
head = new Node<E>(null,head); //creation of the dummy node
14+
size = 0;
15+
}
16+
public int getSize(){ return size;} // getter for the size... needed because size is private.
17+
public void append(E value){ // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
18+
if(value == null){
19+
throw new NullPointerException("Cannot add null element to the list"); // we do not want to add null elements to the list.
20+
}
21+
head.next = new Node<E>(value,head); //head.next points to the last element;
22+
size++;}
23+
public E remove(int pos){
24+
if(pos>size || pos< 0){
25+
throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); //catching errors
26+
}
27+
Node<E> iterator = head.next;
28+
Node<E> before = head; //we need to keep track of the element before the element we want to remove we can see why bellow.
29+
for(int i = 1; i<=pos; i++){
30+
iterator = iterator.next;
31+
before = before.next;
32+
}
33+
E saved = iterator.value;
34+
before.next = iterator.next; // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
35+
iterator.next = null; // scrubbing
36+
iterator.value = null;
37+
return saved;
38+
39+
}
40+
41+
}
42+

0 commit comments

Comments
 (0)