Merge pull request #8231 from radhe-sravan/master

BAEL-3453 - Circular linked list Java implementation
This commit is contained in:
Jonathan Cook 2019-11-27 22:59:10 +01:00 committed by GitHub
commit 9cae3c7c86
2 changed files with 146 additions and 0 deletions

View File

@ -0,0 +1,90 @@
package com.baeldung.list;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CircularLinkedList {
final Logger LOGGER = LoggerFactory.getLogger(CircularLinkedList.class);
private Node head = null;
private Node tail = null;
public void addNode(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
tail.nextNode = newNode;
}
tail = newNode;
tail.nextNode = head;
}
public boolean containsNode(int searchValue) {
Node currentNode = head;
if (head == null) {
return false;
} else {
do {
if (currentNode.value == searchValue) {
return true;
}
currentNode = currentNode.nextNode;
} while (currentNode != head);
return false;
}
}
public void deleteNode(int valueToDelete) {
Node currentNode = head;
if (head != null) {
if (currentNode.value == valueToDelete) {
head = head.nextNode;
tail.nextNode = head;
currentNode = null;
} else {
do {
Node nextNode = currentNode.nextNode;
if (nextNode.value == valueToDelete) {
currentNode.nextNode = nextNode.nextNode;
nextNode = null;
break;
}
currentNode = currentNode.nextNode;
} while (currentNode != head);
}
}
}
public void traverseList() {
Node currentNode = head;
if (head != null) {
do {
LOGGER.info(currentNode.value + " ");
currentNode = currentNode.nextNode;
} while (currentNode != head);
}
}
}
class Node {
int value;
Node nextNode;
public Node(int value) {
this.value = value;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.list;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CircularLinkedListUnitTest {
@Test
public void givenACircularLinkedList_WhenAddingElements_ThenListContainsThoseElements() {
CircularLinkedList cll = createCircularLinkedList();
assertTrue(cll.containsNode(8));
assertTrue(cll.containsNode(37));
}
@Test
public void givenACircularLinkedList_WhenLookingForNonExistingElement_ThenReturnsFalse() {
CircularLinkedList cll = createCircularLinkedList();
assertFalse(cll.containsNode(11));
}
@Test
public void givenACircularLinkedList_WhenDeletingElements_ThenListDoesNotContainThoseElements() {
CircularLinkedList cll = createCircularLinkedList();
assertTrue(cll.containsNode(13));
cll.deleteNode(13);
assertFalse(cll.containsNode(13));
assertTrue(cll.containsNode(1));
cll.deleteNode(1);
assertFalse(cll.containsNode(1));
assertTrue(cll.containsNode(46));
cll.deleteNode(46);
assertFalse(cll.containsNode(46));
}
private CircularLinkedList createCircularLinkedList() {
CircularLinkedList cll = new CircularLinkedList();
cll.addNode(13);
cll.addNode(7);
cll.addNode(24);
cll.addNode(1);
cll.addNode(8);
cll.addNode(37);
cll.addNode(46);
return cll;
}
}