How To Search In A Link List
Today i will show you how to search in a link list and count how many times a number has been repeated in a link list.I will use C++ for this purpose we will create 3 functions inserting function , printing function and then the searching function .
1 Code
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
struct node*head;
void add(int roll_num)
{
struct node *temp=new node();
temp->data=roll_num;
temp->next=head;
head=temp;
}
void print()
{
struct node*temp=head;
cout<<"List is"<<endl;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
int searchnode(int num)
{
node *current=head;
int repeat=0;
while(current!=NULL)
{
if(current->data==num)
{
repeat++;
}
current=current->next;
}
if(repeat!=0)
return repeat;
else
return 0;
}
int main()
{
head=NULL;
int num,repeat;
cout<<"Enter the value you want to search"<<endl;
cin>>num;
add(1187);
add(1187);
add(1234);
print();
repeat=searchnode(num);
if(repeat!=0)
cout<<"The Value "<<num<<" Is Repeated "<<repeat<<" Times"<<endl;
else
cout<<"Value Doesnot exsist";
}
2 Explanation
So in the searchnode function the WHILE Loop will go until it reaches the NULL node then after that in the IF statement if the data which is in the current node is equal to the number we are searching then we increment repeat by one and then we move towards the next node if noting is found the repeat will remain zero.Now if the data exists it will tell that the data exists and how many times it was repeated if repeat is zero then the number doesn't exists.
3 Conclusion
Today we just build an application that searches in the link list which we did in the most easy way .IF you have any type of problem please let me know otherwise thanks for coming.
Comments
Post a Comment