Count number of nodes - DS TUTORIAL - onwnxcvnne
Headlines News :
Home » , , » Count number of nodes - DS TUTORIAL

Count number of nodes - DS TUTORIAL

Written By jomon on Monday 16 April 2012 | 09:05

demonstrate how to count the number of nodes present in the linked list.

Code:

# include <stdio.h>
# include <stdlib.h>
struct node
{

int
data;
struct
node *link;
};

struct
node *insert(struct node * , int);
int
countnode(struct node*);
void
printlist (struct node *);

struct
node *insert(struct node *p , int n)
{

struct
node *temp;
if
(p==NULL)
{

p=(struct node *)malloc(sizeof(struct node));
if
(p==NULL)
{

printf("Error Occurred\n");
exit(0);
}

p-> data = n;
p-> link = NULL;
}

else

{

temp = p;
while
(temp-> link!= NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if
(temp -> link == NULL)
{

printf("Error Occurred\n");
exit(0);
}

temp = temp-> link;
temp-> data = n;
temp-> link = NULL;
}

return
(p);
}



void
printlist ( struct node *p )
{

printf("The data in the list are\n");
while
(p!= NULL)
{

printf("%d\t",p-> data);
p = p-> link;
}
}


int
countnode (struct node *p )
{

int
count=0;
while
(p != NULL)
{

count ++;
p = p->link;
}

return
(count);
}



void
main()
{

int
n;
int
x;
struct
node *start = NULL ;
printf("Enter number of nodes to be created \n");
scanf("%d",&n);
while
( n-- > 0 )
{

printf( "Enter the data for node\n");
scanf("%d",&x);
start = insert ( start ,x);
}

printlist ( start );
n = countnode(start);
printf("\nThe number of nodes in a list are: %d\n",n);
}

Output:

Share this article :

0 comments:

Speak up your mind

Tell us what you're thinking... !

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. onwnxcvnne - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger