You’ve written function create()
in a bad way (for
loop to be more detailed).
You should write it in this way:
for(int i = 1; i < n; i++) {
struct node *x= malloc(sizeof(struct node));
x->data=a[i];
x->next=NULL;
far->next=x; //connects the node far to x
far=x; //shifts the node far to x now far will be pointing to x
}
(you must start counting from 1, because zeroth element is already initialized and filled)
Additional protip: you can remove pointer casts near malloc()
function calls, because C allows to implicitly convert void *
to another pointer types.
You should also add free()
calls to release memory occupied by your list at the end of main()
function.
solved display of a single linked list is not as expected [closed]