0

My university professor gave us the following code but i feel like the 3rd row from the bottom should be

temp -> next = curr -> next -> next

If I am mistaken why is it correct ?

!!Note, the new node should be placed in the middle of the linked list and not in an edge!!


void insert_list (struct node *head, int pos) {
    int k;
    struct node *temp, *curr;
    curr = ihead;
    for (k=1; k<pos; k++)
       curr = curr -> next;
    temp = (struct node *) malloc (sizeof (struct node));
    temp -> next = NULL;
    gets (temp -> student);
    scanf ("%d", &temp -> am);
    temp -> next = curr -> next;
    curr -> next = temp;
}
2
  • Side note: this code has some issues. What happens if head == NULL or if pos > the length of the list? Also, there seems to be a typo: head and ihead? Other issues that might popup: if malloc returns NULL, or scanf fails. And then there's gets(): Why is the gets function so dangerous that it should not be used? Commented Jun 1, 2022 at 18:59
  • @JohnnyMopp we just started learning about linked lists, thanks for the feedback Commented Jun 1, 2022 at 19:01

1 Answer 1

1

If you have the elements A B C D and you insert X between B and C, then:

In the beginning:

  • B would be curr
  • C would be curr->next
  • D would be curr->next->next

After your function:

  • B would still be curr
  • X would be curr->next and temp
  • C would be temp->next and curr->next->next
  • D would be temp->next->next and curr->next->next->next

so as to have the linked list: A B X C D.

If you used curr->next->next, X->next would point to D and you would lose C in the process.

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

3 Comments

oh I can see what you are talking about. Thanks for the help, I am new to this!
No worries, you're welcome. If that answered your question, please consider marking the answer as accepted.
Of course I will!

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.