Search an element in a Linked List (Iterative and Recursive)

Write a function that searches a given key ‘x’ in a given singly linked list. The function should return true if x is present in linked list and false otherwise.

bool search(Node *head, int x)

For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then function should return false. If key to be searched is 14, then the function should return true.

Iterative Solution

2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
a) current->key is equal to the key being searched return true.
b) current = current->next
4) Return false

Following is iterative implementation of above algorithm to search a given key.

C#

Output:

Yes

Recursive Solution

1) If head is NULL, return false.
2) If head's key is same as x, return true;
2) Else return search(head->next, x)

Following is recursive implementation of above algorithm to search a given key.

Output:

Yes

C#

Output:

Yes

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

24

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.