Skip to content

Commit cc0e351

Browse files
search in singly linked list using recursion
1 parent e98693b commit cc0e351

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package DataStructures.Lists;
2+
3+
public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
4+
public static void main(String[] args) {
5+
SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion();
6+
for (int i = 1; i <= 10; ++i) {
7+
list.insert(i);
8+
}
9+
10+
for (int i = 1; i <= 10; ++i) {
11+
assert list.search(i);
12+
}
13+
assert !list.search(-1)
14+
&& !list.search(100);
15+
}
16+
17+
/**
18+
* Test if the value key is present in the list using recursion.
19+
*
20+
* @param node the head node.
21+
* @param key the value to be searched.
22+
* @return {@code true} if key is present in the list, otherwise {@code false}.
23+
*/
24+
private boolean searchRecursion(Node node, int key) {
25+
return node != null && (node.value == key || searchRecursion(node.next, key));
26+
}
27+
28+
@Override
29+
public boolean search(int key) {
30+
return searchRecursion(getHead(), key);
31+
}
32+
}

0 commit comments

Comments
 (0)