1

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please further explain the difference between the two cases?
@Smokie The first is an assignment of a pointer next itself to the pointer pointed to by l; the second one is an assignment of a pointer to next to the variable l itself.
1

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).

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.