【发布时间】:2010-12-04 21:25:47
【问题描述】:
我正在尝试创建一个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;
编辑2: 这个似乎也不起作用,我遇到了段错误。
//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;
【问题讨论】:
-
嗨 Reti,我在回复中回复了 edit1。如果遇到段错误,请检查您是否正确分配和删除了 tmp 变量。
标签: c++ linked-list swap