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;
}
  • 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?](https://stackoverflow.com/q/1694036) – 001 Jun 01 '22 at 18:59
  • @JohnnyMopp we just started learning about linked lists, thanks for the feedback – Dns Stratos Jun 01 '22 at 19:01

1 Answers1

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.

PhilMasteG
  • 3,095
  • 1
  • 20
  • 27