Write a C 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
C Programming:
#include<stdio.h>
#include<stdlib.h>
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)
{
struct node* current = head;
while (current != NULL)
{
if (current->key == x)
return true;
current = current->next;
}
return false;
}
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)? printf("Yes") : printf("No");
return 0;
}
[ad type=”banner”]
Output:
Yes
Recursive Solution
bool search(head, x)
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)
C Programming:
#include<stdio.h>
#include<stdlib.h>
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)? printf("Yes") : printf("No");
return 0;
}
[ad type=”banner”]
Output:
Yes