11package com .baeldung .list ;
22
3+ import org .slf4j .Logger ;
4+ import org .slf4j .LoggerFactory ;
5+
36public class CircularLinkedList {
47
5- Node head = null ;
6- Node tail = null ;
8+ final Logger LOGGER = LoggerFactory .getLogger (CircularLinkedList .class );
9+
10+ private Node head = null ;
11+ private Node tail = null ;
712
813 public void addNode (int value ) {
914
1015 Node newNode = new Node (value );
1116
12- // If no elements are present, make the newly addNodeed node as head
1317 if (head == null ) {
1418 head = newNode ;
15- }
16- // If there are elements already present, the existing tail should point to new node
17- else {
19+ } else {
1820 tail .nextNode = newNode ;
1921 }
2022
21- // Irrespective of whether or not elements are added, assign the
22- // tail to newNode and the nextNode for tail as head
2323 tail = newNode ;
2424 tail .nextNode = head ;
2525 }
2626
2727 public boolean containsNode (int searchValue ) {
2828
29- // Start traversing from the head
3029 Node currentNode = head ;
3130
32- // If list is empty no need of traversal and can return false
3331 if (head == null ) {
3432 return false ;
3533 } else {
3634 do {
37- // Compares the search value with each node value present in the list
3835 if (currentNode .value == searchValue ) {
3936 return true ;
4037 }
@@ -46,24 +43,16 @@ public boolean containsNode(int searchValue) {
4643
4744 public void deleteNode (int valueToDelete ) {
4845
49- // Start traversing from the head
5046 Node currentNode = head ;
5147
52- // If list is non empty
5348 if (head != null ) {
54- // If the node to delete is the head node itself,
55- // update the head as the next node of current head
56- // and the nextNode of tail as new head
5749 if (currentNode .value == valueToDelete ) {
5850 head = head .nextNode ;
5951 tail .nextNode = head ;
6052 currentNode = null ;
6153 } else {
6254 do {
63- // Fetch the next node of current node
6455 Node nextNode = currentNode .nextNode ;
65- // If the value to delete matches the next node's value,
66- // update the next node of current node as the next node of present next node
6756 if (nextNode .value == valueToDelete ) {
6857 currentNode .nextNode = nextNode .nextNode ;
6958 nextNode = null ;
@@ -77,12 +66,11 @@ public void deleteNode(int valueToDelete) {
7766
7867 public void traverseList () {
7968
80- // Start traversing from the head
8169 Node currentNode = head ;
8270
8371 if (head != null ) {
8472 do {
85- System . out . print (currentNode .value + " " );
73+ LOGGER . info (currentNode .value + " " );
8674 currentNode = currentNode .nextNode ;
8775 } while (currentNode != head );
8876 }
@@ -99,4 +87,4 @@ public Node(int value) {
9987 this .value = value ;
10088 }
10189
102- }
90+ }
0 commit comments