I tried to write a program to add some nodes in a linked list. When I compile and run it, I get a segmentation fault. Could anyone tell me where the problem is?
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* link;
}; // define a structure
struct node* first; //the first node;
void insert(int n) // function to insert element at the end
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
struct node* ptr = first;
temp->data = n;
temp->link = NULL;
while(ptr->link != NULL)
{
ptr = ptr->link;
}
ptr->link = temp;
}
void Print() //function to print out the element
{
struct node* ptr = first;
printf("List is:");
while(ptr != NULL)
{
printf("%d ",ptr->data);
ptr = ptr->link;
}
}
int main()
{
int i,k,n;
first = NULL;
printf("How many numbers you want to insert?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter:");
scanf("%d",&k);
insert(k);
}
Print(); //Print out the linked list
return 0;
}
