Reputation: 173
I have the following single linked list,I always get the length as 1,even if i push 3 elements,and always only one node is created.Please help.Thanks.
#include <stdio.h>
struct node
{
int data;
struct node *next;
};
void push(struct node **head,int data)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data=data;
if(*head == NULL)
{
*head=temp;
}
else
{
temp->next=*head;
*head=temp;
}
}
int length(struct node *head)
{
struct node *temp = head;
int count=0;
if(temp !=NULL)
{
count++;
printf("%d",temp->data);
temp=temp->next;
}
return count;
}
int main()
{
int a;
struct node *head=NULL;
push(&head,1);
push(&head,2);
push(&head,3);
a=length(head);
printf("%d",a);
return 0;
}
Upvotes: 1
Views: 301
Reputation: 44250
# include <stdlib.h>
void push(struct node **head,int data)
{
struct node *temp;
temp = malloc (sizeof *temp);
temp->data = data;
temp->next = *head;
*head = temp;
}
Upvotes: 0
Reputation: 7955
The error comes from push()
function. If head
is not null you need to iterate through the list to the last node. And as said before while
instead if
Upvotes: 1
Reputation: 1421
Have you noticed the structure of your length method? You are using an if statement where a loop would be appropriate. You are getting the answer of 1 because you are only executing the count ++ statement once.
Hope this helps.
Upvotes: 1
Reputation: 168876
In your length
function, change this line:
if(temp !=NULL)
to this:
while(temp != NULL)
Upvotes: 2