From cc0e3510e2ff76d346c5458c2c24697539f618e1 Mon Sep 17 00:00:00 2001 From: shellhub Date: Tue, 22 Sep 2020 11:23:45 +0800 Subject: [PATCH] search in singly linked list using recursion --- .../SearchSinglyLinkedListRecursion.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 DataStructures/Lists/SearchSinglyLinkedListRecursion.java diff --git a/DataStructures/Lists/SearchSinglyLinkedListRecursion.java b/DataStructures/Lists/SearchSinglyLinkedListRecursion.java new file mode 100644 index 000000000..10755c0b8 --- /dev/null +++ b/DataStructures/Lists/SearchSinglyLinkedListRecursion.java @@ -0,0 +1,32 @@ +package DataStructures.Lists; + +public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { + public static void main(String[] args) { + SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion(); + for (int i = 1; i <= 10; ++i) { + list.insert(i); + } + + for (int i = 1; i <= 10; ++i) { + assert list.search(i); + } + assert !list.search(-1) + && !list.search(100); + } + + /** + * 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); + } +}