I am trying to make a swapNode function that can take any two nodes and swap them. I\'ve made an algorithm that works if they\'re at least 2 nodes away, but I c
In most real-life scenarios, swapping the values will be the best solution:
void swapNode(call * &head, call * &first, call * &second) {
// swap values, assuming the payload is an int:
int tempValue = first->value;
first->value = second->value;
second->value = tempValue;
}
If that's not allowed, then you want to do a similar-style swap on the ->next instead of the ->value component. And then do another swap on the firstPrev->next and secondPrev->next components. Watch out for the special case where first or second == head.
You will have to also swap the next component of the previous node, otherwise the linked list will not remain joined together. Note that my struct is called node.
int swapNode( node *&head * &first, node * &second)
{
//first we will declare the
//previous of the swapping nodes
node *firstprev=NULL;
node*secprev=NULL;
node*current=head;
//set previous first
while(current->next!=first)
{
current=current->next;
}
firstprev=current;
//seting 2nd previous
while(current->next!=second)
{
current=current->next;
}
// swap values, assuming the payload is an int:
int tempValue = first->value;
first->value = second->value;
second->value = tempValue;
//swaping next of the nodes
firstprev->next=second;
secprev->next=first;
return;
}