Reputation: 171
I am unable to figure out why am I counting 1 less in len() function defined below. len() function is supposed to count the number of elements in my linked list.
struct node {
int data;
struct node* link;
};
typedef struct node node;
node *root=NULL;
void append(void);
int len(void);
int main(void) {
printf("\nCurrent length of list:\t%d\n",len());
append();
printf("\nCurrent length of list:\t%d\n",len());
append();
printf("\nCurrent length of list:\t%d\n",len());
append();
printf("\nCurrent length of list:\t%d\n",len());
return 0;
}
void append(void) {
node *tmp;
tmp=(node *)malloc(sizeof(node));
printf("\nEnter data value\t\n");
scanf("%d", &tmp->data);
tmp->link=NULL;
if(root==NULL){
root=tmp;
}
else{
node *ptr=root;
while(ptr->link!=NULL){
ptr=ptr->link;
}
ptr->link=tmp;
}
}
int len(void) {
int cnt=0;
if(root==NULL)
return 0;
node *tmp=root;
while(tmp->link!=NULL){
++cnt;
tmp=tmp->link;
}
return cnt;
}
Current length of list: 0 // call to len(), Expected output : Correct
Enter data value 20 // call to append()
Current length of list: 0 // call to len(), Expected output : 1
Enter data value 191 // call to append()
Current length of list: 1 // call to len(), Expected output : 2
Enter data value 22 // call to append()
Current length of list: 2 // call to len(), Expected output : 3
Upvotes: 0
Views: 97
Reputation: 514
You didn't count the last element. Try to trace your code.
If your linked list looks as the following
elem1 -> elem2 -> elem3 -> NULL
You count the elements 1 and 2 but not 3 because the link
field of 3 is NULL.
Alter your code to the following and it will work
int len(void){
int cnt=0;
node *tmp=root;
while(tmp!=NULL){
++cnt;
tmp=tmp->link;
}
return cnt;
}
Upvotes: 1