I am learning singly-linked lists in C and trying to link components of an array. I have written a few lines of code but it is not giving required results i-e making and printing linked list from array. Can someone please explain why it is not working? Thanks
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int data;
struct list *next;
}
list;
list *createlinkedlist(int *arr);
void printlist(list * head);
int main(void)
{
int arr[]={1,2,3,4,5};
list *head=NULL;
head = createlinkedlist(arr);
printlist(head);
}
list *createlinkedlist(int *arr)
{
list *head=NULL;
list *temp=NULL;
list *p=NULL;
for (int j=0, O=sizeof(arr); j<O; j++)
{
temp= (list*)malloc(sizeof(list));
temp->next = NULL;
if(head == NULL)
head=temp;
else
{
p=head;
while(p->next!=NULL)
{
p=p->next;
}
p->next = temp;
}
}
return head;
}
void printlist(list *head)
{
list * p = head;
while (p !=NULL)
{
printf("%d\n", p->data);
p = p->next;
}
}