JavaAlgorithms/DataStructures/Lists/SearchSinglyLinkedListRecursion.java

32 lines
900 B
Java
Raw Permalink Normal View History

package DataStructures.Lists;
public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion();
for (int i = 1; i <= 10; ++i) {
list.insert(i);
}
2020-10-24 18:23:28 +08:00
for (int i = 1; i <= 10; ++i) {
assert list.search(i);
}
2020-10-24 18:23:28 +08:00
assert !list.search(-1) && !list.search(100);
}
2020-10-24 18:23:28 +08:00
/**
* Test if the value key is present in the list using recursion.
*
* @param node the head node.
* @param key the value to be searched.
* @return {@code true} if key is present in the list, otherwise {@code false}.
*/
private boolean searchRecursion(Node node, int key) {
return node != null && (node.value == key || searchRecursion(node.next, key));
}
@Override
public boolean search(int key) {
return searchRecursion(getHead(), key);
}
}