Sunday 7 April 2013

TO FIND EVEN AND ODD ELEMENTS IN A LINKED LIST


#include<stdio.h>
#include<conio.h>
typedef struct NUM
{
int data;
struct NUM *link;
}num;
num *createnode()
{
num *nn=NULL;
nn=(num*)malloc(sizeof(num));
if(nn==NULL)
{
printf("\n insufficient memory");
exit(0);
}//end if
return(nn) ;
} //end createnode
num *create()
{
num *hn=NULL ,*cn=NULL ,*nn=NULL;
int i,n;
printf("\n enter no of node ");
scanf("%d",&n);
printf("\n enter data\t");
for(i=0;i<n;i++)
{
nn=createnode();
scanf("%d",&nn->data);
nn->link=NULL;
if(hn==NULL)
{
hn=nn;
cn=nn;
}//end if
else
{
cn->link=nn;
cn=nn;
}
}//end for
return(hn);
}//end create
void display(num *hn)
{
num *cn=NULL;
int cnt_nonzero=0,cnt_even=0,cnt_odd=0;
num *temp=NULL;
printf("\n data present in link list is ");
for(cn=hn;cn!=NULL;cn=cn->link)
{
printf("%d",cn->data);
}//end for
/*following code counts the nonzero,even,odd*/
temp=hn;
while(temp!=NULL)
{
if(temp->data!=0)
{
cnt_nonzero++;
}
if(temp->data!=0)
{
if((temp->data)%2==0 ){
cnt_even++;}
if((temp->data)%2!=0){
cnt_odd++;}}
temp=temp->link;
}
printf("\nThe number of non-zero elements is %d",cnt_nonzero);
printf("\nThe number of even elements is %d",cnt_even);
printf("\nThe number of odd elements is %d",cnt_odd);
}
void main()
{
num *hn,*nn,*pn;
int ch;
clrscr();
hn= create();
display(hn);
getch();
}
Output:

enter no of node 5
 enter data     1
2
3
4
5
 data present in link list is 12345
The number of non-zero elements is 5
The number of even elements is 2
The number of odd elements is 3

No comments:

Post a Comment