From e98693b14036dd482b9471444c815038ed2e720a Mon Sep 17 00:00:00 2001 From: shellhub Date: Tue, 22 Sep 2020 11:09:19 +0800 Subject: [PATCH] search element --- DataStructures/Lists/SinglyLinkedList.java | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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);