Skip to content

Commit e98693b

Browse files
search element
1 parent 093cc37 commit e98693b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

DataStructures/Lists/SinglyLinkedList.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,24 @@ public int count() {
194194
return count;
195195
}
196196

197+
/**
198+
* Test if the value key is present in the list.
199+
*
200+
* @param key the value to be searched.
201+
* @return {@code true} if key is present in the list, otherwise {@code false}.
202+
*/
203+
public boolean search(int key) {
204+
Node cur = head;
205+
while (cur != null) {
206+
if (cur.value == key) {
207+
return true;
208+
}
209+
cur = cur.next;
210+
}
211+
return false;
212+
}
213+
214+
197215
@Override
198216
public String toString() {
199217
if (size == 0) {
@@ -227,6 +245,12 @@ public static void main(String[] arg) {
227245
list.insertNth(1, 4);
228246
assert list.toString().equals("10->7->5->3->1");
229247

248+
/* Test search function */
249+
assert list.search(10)
250+
&& list.search(5)
251+
&& list.search(1)
252+
&& !list.search(100);
253+
230254
/* Test delete function */
231255
list.deleteHead();
232256
list.deleteNth(1);

0 commit comments

Comments
 (0)