I am defining head as a global variable. The user enters integers which should be appended to a singly linked list. I implemented the append function, but it gives me a segmentation fault.
void Append(int x)
{
struct Node *temp, *current;
temp = (struct Node*)malloc(sizeof(struct Node));
temp -> data = x;
temp -> next = NULL;
if(head->next ==NULL)
{
head = temp;
}
else{
//current = (struct Node*)malloc(sizeof(struct Node));
current = head;
while(1)//current != NULL)
{
if(current->next ==NULL)
{
current =current -> next;
printf("added to the end\n");
break;
}
current = current -> next;
}
}
}
The main function is given below:
int main()
{
//create empty List
head =NULL;
printf("How many numbers?\n");
int n,i,x;
scanf("%d",&n);
for(i =0; i<n; i++)
{
printf("Enter the number\n");
scanf("%d",&x);
//Insert(x);
Append(x);
Print();
}
return 0;
}
if(current->next ==NULL){current -> next = temp,;