我正在尝试制作一个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;
}
编辑:我现在把它作为我的交换部分,但它似乎仍然无法正常工作
//swap firstPrev-> next with second->next
tmp = firstPrev->next;
second->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;