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.
#i开发者_开发问答nclude <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;
}
Replace if
by while
in the length function
In your length
function, change this line:
if(temp !=NULL)
to this:
while(temp != NULL)
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.
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
# 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;
}
精彩评论