search element

This commit is contained in:
shellhub 2020-09-22 11:09:19 +08:00
parent 093cc37806
commit e98693b140

View File

@ -194,6 +194,24 @@ public class SinglyLinkedList {
return count; 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 @Override
public String toString() { public String toString() {
if (size == 0) { if (size == 0) {
@ -227,6 +245,12 @@ public class SinglyLinkedList {
list.insertNth(1, 4); list.insertNth(1, 4);
assert list.toString().equals("10->7->5->3->1"); 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 */ /* Test delete function */
list.deleteHead(); list.deleteHead();
list.deleteNth(1); list.deleteNth(1);