It was necessary to create a function for swapping two elements of a dynamic list. I did it but the function did not work. Then I was prompted to make a check and I don’t quite understand why it is needed (I marked the lines with the check in the code)

void SwapLst(List* lst, int id1, int id2) { int id; Itm *temp1 = NULL, *temp2 = NULL; Itm *prev1, *prev2, *next1, *next2; lst->cur = lst->bg; while(lst->cur != NULL){ if(lst->cur->id == id1){ temp1 = lst->cur; } if(lst->cur->id == id2){ temp2 = lst->cur; } lst->cur = lst->cur->next; } if(temp1 == NULL || temp2 == NULL) return; prev1 = temp1->prev; prev2 = temp2->prev; next1 = temp1->next; next2 = temp2->next; \\ if(prev1 != NULL){ prev1->next = temp2; } \\ if(prev2 != NULL){ prev2->next = temp1; } \\ if(next1 != NULL){ next1->prev = temp2; } \\ if(next2 != NULL){ next2->prev = temp1; } temp1->next = next2; temp1->prev = prev2; temp2->next = next1; temp2->prev = prev1; if(prev1 == NULL){ lst->bg = temp2; } if(prev2 == NULL){ lst->bg = temp1; } if(next1 == NULL){ lst->end = temp2; } if(next2 == NULL){ lst->end = temp1; } 

}

  • Implementation only for the ring list. Otherwise, as mentioned below, prev and next can be nullptr. Another mistake, which is an error in any implementation: think what will happen if the elements go in a row. let's say temp1 before temp2. What will next1 and prev2 point to? Is this true? - Dmitry Zinenko

1 answer 1

Well, why, why - if, for example, temp1 turned out to be the first element, then the prev for it does not exist, and how then to contact NULL->next ?

  prev1 = temp1->prev; \\ if(prev1 != NULL){ prev1->next = temp2; 
  • one
    It depends on how the List is implemented. If this is a ring list, then it is quite possible. - Dmitry Zinenko