Friday, 11 May 2012

Length of a Linked List in C

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define newa (struct a*) malloc(sizeof(struct a))

struct a
{
int data;
struct a *next;
};

struct a *list();

void main()
{
struct a *f;
int len;
f = NULL;
clrscr();
f = list();
len = length(f);
printf("\n length = %d",len);

struct a *list()
{
struct a *f,*c,*p;
int tdata;
f = NULL;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&tdata);
while( tdata != 0 )
{
c = newa;
if( c == NULL)
{
printf("\n Insuf. mem. ");
exit(0);
}
c->data = tdata;
c->next = NULL;
if( f== NULL)
f = c;
else
p->next = c;
p = c;
printf("\n Enter data ( use 0 to exit ) : ");
scanf("%d",&tdata);
return(f);

int length(struct a *f)
{
int len=0;
struct a *t;
if( f == NULL)
return(0);
t = f;
while( t != NULL )
{
len++;
t = t->next;
}
return(len);
}

No comments:

Post a Comment