Замена узлов в одном связанном списке
Я пытаюсь сделатьswapNode
функция, которая может взять любые два узла и поменять их местами. Я'мы создали алгоритм, который работает, если онипо крайней мере 2 узла, но я могуКажется, что он придумал алгоритм, который будет работать, если они будут ближе друг к другу.
Вот'Вот что я написал до сих пор:
void swapNode(call * &head, call * &first, call * &second){
call * firstPrev = NULL;
call * secPrev = NULL;
call * current = head;
//set previous for first
while((current->next != first) ){
current = current->next;
}
firstPrev = current;
current = head;
//set previous for second
while((current->next != second) ){
current = current->next;
}
secPrev = current;
current = second->next;
//set firstPrev-> next to second
firstPrev->next = second;
//set secPrev->next to first
secPrev->next = first;
//set second->next = first->next
second->next = first->next;
//set first->next to current
first->next = current;
current = head;
while(current->next != NULL){
cout < current->number < endl;
current = current->next;
}
cout < current->number < endl;
}
next = firstPrev->next;
second->next = tmp;
//swap swap first->next with second->next
tmp = first->next;
second->next = first->next;
second->next = tmp;
EDIT2: этот неКажется, тоже не работает, я получаю ошибку сегмента.
//swap previous's->next
tmp =firstPrev->next;
secPrev->next = firstPrev->next;
secPrev->next = tmp;
//swap swap first->next with second->next
tmp = first->next;
second->next = first->next;
second->next = tmp;