Im trying to create linked-list insert function that takes a list (or more correctly a pointer to it) then inserts the value to the end of the list.
void ll_insert(struct ll **l, int n){
struct ll *temp=NULL;
while ( (*l) != NULL){
temp= (*l);
(*l) = (*l)->next;
}
(*l)= (struct ll*)malloc(sizeof(struct ll));
(*l)->n=n;
(*l)->next=NULL;
if (temp) temp->next= (*l);
}
int main(void){
struct ll *l=NULL;
ll_insert(&l, 1);
printf("%d ", l->n);
ll_insert(&l, 1);
ll_insert(&l, 2);
ll_insert(&l, 3);
printf("%d ", l->n);
}
The output after running the code above is 1 3. This is no surprise, since
(*l) = (*l)->next;
updates the list to point to to the end node, and every time I run insert(...) the list's head is updated to point to the end (if im not wrong). What's the way around this?