I am just learning about linked list. While I am trying to insert elements in linked list I am unable to print those inserted elements.
int main()
{
int i,x,n;
struct node* head = NULL;
printf("Enter number of elements to insert into likedlist :");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&x);
insert(head,x);
}
print(head);
}
struct node* insert(struct node* head,int x)
{
struct node* p = (struct node*)malloc(sizeof(struct node));
p->data = x;
p->next = NULL;
if(head == NULL)
{
head = p;
return head;
}
p->next = head;
head = p;
return head;
}
here I am adding the elements to a linked list by changing it's head node(insert_front).
void print(struct node* n)
{
while(n != NULL)
{
printf("%d -> ",n->data);
n = n->next;
}
printf("NULL");
}
So, what's wrong with this code. Output is like this
Sample Input:
Enter number of elements to insert into likedlist :5
Enter elements: 1 2 3 4 5
Sample Output:
NULL