Linked List Creation
Goal:- Creating a linked list and search for a Given Element.
Method-Used:- Simple create a linked list using structure and perform linear search.
Explanation:- It is a linear collection of data elements ,called nodes where each node is divided into two parts:
1. first part conatins the information about node
2. Second part contains the address of the next node in the list.
Linked List vs Array:
we use linked list because insertion and deletion in array is relatively expensive than Linked list.
Arrays occupies a block of memory space ,one cannot simply extend the size of array when additional space is needed.
Program:
#include<iostream>
#include<conio.h>
using namespace std;
struct node {
int info;
node *next;
};
node *create()
{
int n,i,data,;
node *p1,*head1,*temp1;
head1=NULL;
temp1=NULL;
cout<<"\n\tHow many Elements you want to enter:\n";
cout<<"\t";
cin>>n;
cout<<"\n\t Enter Elemnts:\n";
for(i=0;i<n;i++)
{
cout<<"\t";
cin>>data;
if(head1==NULL)
{
p1=new node;
p1->info=data;
p1->next=NULL;
head1=p1;
temp1=p1;
}
else
{
p1=new node;
p1->info=data;
p1->next=NULL;
temp1->next=p1;
temp1=p1;
}
}
p1=head1;
return p1;
}
void display(node *p2)
{
cout<<"\t";
cout<<"Displaying:--\n";
while(p2)
{
cout<<"\t";
cout<<p2->info<<"\t";
p2=p2->next;
}
}
void search(node *p2)
{
int m,count=0;
cout<<"\n\tEnter element to be searched:-\n";
cout<<"\t";
cin>>m;
while(p2)
{
if(p2->info==m){
count++;
p2=p2->next;
}
else
p2=p2->next;
}
cout<<"\t";
cout<<"Element "<<m<<" occurs at "<<count<<" times in list" ;
}
int main()
{
node *p1,*head,*temp;
head=NULL;
temp=NULL;
p1=create();
display(p1);
search(p1);
getch();
}
Output:-
If you want to share more information about topic discussed above or find anything incorrect Please do comments.
0 comments:
Post a Comment