Question description
Once upon a time, in French Canada, there lived a fat old woman named Tante Adela.
She lived alone in her barn with her large grey cat and her cows.
She got up quite early one morning since it was baking day and she had a lot to accomplish.
She carried a pile of wood to her oven outdoors.
she ran across some old school classmates, with whom she reminisced about their school days and a mental exam competition.
One of the competition's requirements was to write a C function that searches a singly linked list for a given key "x." (Iterative).
If x is contained in the linked list, the function should return true; otherwise, it should return false.
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.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node{int data;struct node* next;};
struct node*newNode(int d){
struct node*n=malloc(sizeof(struct node));
n->data=d;n->next=NULL;return n;
}
bool search(struct node* head, int x){
while(head){if(head->data==x)return true;head=head->next;}
return false;
}
int main(){
int n,x,v;
struct node*head=NULL;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&v);
struct node*t=newNode(v);
t->next=head;head=t;
}
scanf("%d",&x);
if(search(head,x))printf("Yes\n");
else printf("No\n");
return 0;
}
0 Comments