1+ package com .thealgorithms .datastructures .lists ;
2+
3+ public class DoubleCircularLinkedList <E > {
4+
5+ private static final class Node <E > {
6+ Node <E > next ;
7+ Node <E > previous ;
8+ E value ;
9+
10+ private Node (E value , Node <E > next ) {
11+ this .value = value ;
12+ this .next = next ;
13+ }
14+ }
15+
16+ private int size ;
17+ private Node <E > head = null ;
18+ private Node <E > tail = null ; // keeping a tail pointer to keep track of the end of the list
19+
20+ public DoubleCircularLinkedList () {
21+ // creation of the dummy node
22+ head = new Node <>(null , null );
23+ tail = head ; // Initially, head and tail point to the dummy node
24+ head .next = head ; // Circular reference to itself
25+ size = 0 ;
26+ }
27+
28+ public int getSize () {
29+ return size ;
30+ }
31+
32+ public void append (E value ) {
33+ if (value == null ) {
34+ throw new NullPointerException ("Cannot add null element to the list" );
35+ }
36+
37+ Node <E > newNode = new Node <>(value , head ); // Create new node pointing to head
38+ if (size == 0 ) {
39+ head .next = newNode ; // Update head's next to point to the new node
40+ newNode .previous = head ; // Update the new node's previous to point to head
41+ tail = newNode ; // Update tail to the new node
42+ } else {
43+ tail .next = newNode ; // Previous tail points to the new node
44+ newNode .previous = tail ;
45+ tail = newNode ;
46+ head .previous = tail ;
47+ }
48+ size ++;
49+ }
50+ @ Override
51+ public String toString () {
52+ if (size == 0 ) {
53+ return "[]" ;
54+ }
55+ StringBuilder sb = new StringBuilder ("[ " );
56+
57+ Node <E > current = head .next ;
58+ while (current != head ) {
59+ sb .append (current .value );
60+ if (current .next != head ) {
61+ sb .append (", " );
62+ }
63+ current = current .next ;
64+ }
65+ sb .append (" ]" );
66+ return sb .toString ();}
67+
68+ public E remove (int pos ) {
69+ if (pos >= size || pos < 0 ) {
70+ throw new IndexOutOfBoundsException ("Position cannot be greater than size or negative" );
71+ }
72+
73+ Node <E > before = head ;
74+ for (int i = 0 ; i < pos ; i ++) {
75+ before = before .next ; // Move to the node before the one to be removed
76+ }
77+
78+ Node <E > destroy = before .next ; // Node to be removed
79+ E saved = destroy .value ; // Save the value to return
80+
81+ before .next = destroy .next ; // Bypass the node to be removed
82+ destroy .next .previous = before ;
83+
84+ if (destroy == tail ) { // If the tail is being removed
85+ tail = before ; // Update the tail
86+ }
87+
88+ size --;
89+ return saved ; // Return the removed value
90+ }
91+
92+ public static void main (String [] args )
93+ {
94+ DoubleCircularLinkedList <String > k = new DoubleCircularLinkedList <>();
95+ k .append ("khalid" );
96+ k .append ("fahad" );
97+ k .append ("nora" );
98+ System .out .println (k .getSize ());
99+ System .out .println (k .toString ());
100+ }
101+ }
0 commit comments