I need help creating a C program Function. The prototype is int search(struct no
ID: 3881544 • Letter: I
Question
I need help creating a C program Function. The prototype is int search(struct node *list, int number)
This function should search the linked list for a node continaing the given number. It returns 1 if the node is found, 0 if it is not found.
This is how the struct node is set up:
struct node
{
int data;
struct node *next;
};
Where data is the integer actually stored in the list and next is the momeory location of the next element, or NULL for the end of the list.
To add a number to the list, create a new node, search the list for the proper point to insert the new node, adjust the prior node's “next” field to point to the new node, and adjust the new node's “next” field accordingly.
Similar actions are taken for printing, searching and deleting.
You should use malloc(sizeof(struct node)) to get the address of a new node; and free(ptr) to release a node from memory (after deleting it, or at the end of the program).
Thanks in advanced!
Explanation / Answer
/*Most of the operations explained in your problem statement itself
So i am going to explain that how we can search in linked list
Steps:
Create new pointer called ptr and assign value of head to it
then traverse whole complete list till NULL pointer reached using while loop (like array)
compare ptr.key==x if present then return 1
return 0 if not present in linked list
I added add() method to add new nodes to linked list
and search() method to search key
*/
// Iterative C program to search an element in linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int key;
struct Node* next;
};
//method to add new key ant front of the linked list
struct node * add(struct node *head, int key)
{
/* create a new node*/
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* adding key to new node*/
new_node->key = key;
/* link the old list off the new node */
new_node->next = head;
/* move the head to point to the new node */
head = new_node;
return head;
}
/* Checks whether the value x is present in linked list */
int search(struct node* head, int x)
{
struct node* ptr = head; // Initialize ptr
while (ptr != NULL)
{
if (ptr->key == x)
return 1;
//getting next pointer
ptr = ptr->next;
}
return 0;
}
int main()
{
/* Start with the empty list , creating head pointer of the list */
struct ode* head = NULL;
/* Use add() to construct below list
11->30->90->21->34 */
head=add(head, 11);
head=add(head, 30);
head=add(head, 90);
head=add(head, 21);
head=add(head, 34);
struct node *ptr=head;
//passing 21 to check if present
int x=search(head, 21);
if(x==1)
printf("Yes");
else
printf("No");
x=search(head, 1);
if(x==1)
printf("Yes");
else
printf("No");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.