Reputation: 12040
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?
Upvotes: 1
Views: 3543
Reputation: 89
if you don't move the pointer l, then it remains at the head of the list. First assign l to temp, then move temp along the list but leave pointer l alone.
Upvotes: 0
Reputation: 726489
You are not using the pointer to pointer correctly: this line in the while
loop
(*l) = (*l)->next;
should be
l = &((*l)->next);
If you use it that way, you wouldn't need your temp
variable at all.
Since this is C, not C++, it is OK to not cast malloc
.
Upvotes: 3
Reputation: 49803
Your function should only change *l if it is inserting into an empty list, as this is the only case where the first element of the list changes. This can be accomplished by using a local variable instead of *l inside of your function for those cases (initialized to *l).
Upvotes: 1