I can’t make a normal function to replace elements in a singly linked list. The swap_val function does not work correctly. If you swap 2 adjacent elements, the program just crashes.
And by the way, if you take the 0th and for example the 3rd element, then the program also works incorrectly. Help please, I can’t understand.
Here is the code for the program: https://pastebin.com/CKPXRGSC
Answer 1
When exchanging two elements that are next to each other, you need to do it differently. Further, you need to take into account if the element is the first in the list, then it does not have the previous one. When changing the first element, remember to change the head variable in the class.
template<typename T>
void List<T>::swap_val(int ind_1, int ind_2){
Node<T> *p1, *prev_p1, *p2, *prev_p2, *tmp_pos;
Node<T> *current = this->head;
if(ind_1){
prev_p2 = head;
for(int i = 1; i < ind_1; i++)
prev_p2 = prev_p2->pNext;
p2 = prev_p2->pNext;}
else{
// if the index is zero, then the previous pointer0
prev_p2=0;p2=head;}
if(ind_2){
prev_p1 = head;
for(int i = 1; i < ind_2; i++)
prev_p1 = prev_p1->pNext;
p1 = prev_p1->pNext;}
else{
// if the index is zero, then the previous pointer0
prev_p1=0;p1=head;}
if(p2->pNext == p1){
// if the elements are nearby, then the exchange is done by-to another
p2->pNext = p1->pNext;
p1->pNext=p2;
// check if there is-whether the previous
if(prev_p2)prev_p2->pNext=p1;}
else
if(p1->pNext == p2){
// if the elements are nearby, then the exchange is done by-to another
p1->pNext = p2->pNext;
p2->pNext =p1;
// check if there is-whether the previous
if(prev_p1)prev_p1->pNext=p2;}
else{
// standard exchange
tmp_pos = p1->pNext;
p1->pNext = p2->pNext;
p2->pNext = tmp_pos;
// check if there is-whether the previous
if(prev_p1) prev_p1->pNext = p2;
if(prev_p2) prev_p2->pNext = p1; }
// if the index was at the beginning, then we change the beginning in the class
if(ind_1 == 0)head = p1;
if(ind_2 == 0)head = p2;
}