diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 7c10f8cf..668a40da 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -194,6 +194,24 @@ public class SinglyLinkedList { return count; } + /** + * Test if the value key is present in the list. + * + * @param key the value to be searched. + * @return {@code true} if key is present in the list, otherwise {@code false}. + */ + public boolean search(int key) { + Node cur = head; + while (cur != null) { + if (cur.value == key) { + return true; + } + cur = cur.next; + } + return false; + } + + @Override public String toString() { if (size == 0) { @@ -227,6 +245,12 @@ public class SinglyLinkedList { list.insertNth(1, 4); assert list.toString().equals("10->7->5->3->1"); + /* Test search function */ + assert list.search(10) + && list.search(5) + && list.search(1) + && !list.search(100); + /* Test delete function */ list.deleteHead(); list.deleteNth(1);