C++ Program For Searching An Element In A Linked List
Last Updated :
09 Mar, 2023
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:
1) Initialize a node pointer, current = head.
2) Do following while current is not NULL
a) current->key is equal to the key being searched return true.
b) current = current->next
3) Return false
Following is iterative implementation of above algorithm to search a given key.
C++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int key;
Node* next;
};
void push(Node** head_ref, int new_key)
{
Node* new_node = new Node();
new_node->key = new_key;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
bool search(Node* head, int x)
{
Node* current = head;
while (current != NULL)
{
if (current->key == x)
return true ;
current = current->next;
}
return false ;
}
int main()
{
Node* head = NULL;
int x = 21;
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
search(head, 21)? cout<< "Yes" : cout<< "No" ;
return 0;
}
|
Output:
Yes
Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Recursive Solution:
bool search(head, x)
1) If head is NULL, return false.
2) If head's key is same as x, return true;
3) Else return search(head->next, x)
Following is the recursive implementation of the above algorithm to search a given key.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node* next;
};
void push( struct Node** head_ref,
int new_key)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->key = new_key;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
bool search( struct Node* head, int x)
{
if (head == NULL)
return false ;
if (head->key == x)
return true ;
return search(head->next, x);
}
int main()
{
struct Node* head = NULL;
int x = 21;
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
search(head, 21)? cout << "Yes" : cout << "No" ;
return 0;
}
|
Output:
Yes
Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(n), due to recursive call stack where n represents the length of the given linked list.
Please refer complete article on Search an element in a Linked List (Iterative and Recursive) for more details!
Share your thoughts in the comments
Please Login to comment...