Home > Back-end >  Insertion of node in a linked list
Insertion of node in a linked list

Time:06-02

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;
}

CodePudding user response:

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.

  • Related