recent

Search an element in a Linkead List (Iterative Method)

Iterative Method Search an element in a Linked List:-
1) Initialize a node pointer, current = head.
2) Do following while current is not NULL
    a)search until current->data is Not equal to the key being searched(Loop terminate when Element          match with current->data).
    b) current = current->next
3.Print a message Node Found or Not.

#include<stdio.h>
#include<stdlib.h>

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

int search(struct node *head,int key)
{
struct node *current;
current=head;

while(current!=NULL && current->data!=key)
{
current=current->next;
}

if(current!=0)
{
printf("Node found:%d\n\n",current->data);
}
else
printf("Node Not found\n\n");

}

main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);

search(head,3);
search(head,13);
search(head,333);

}
Powered by Blogger.