我希望从队列中删除一个设置节点。假设我按名称-ID搜索选择节点。我知道如何从队列的前面删除一些东西,但是对于如何在用户设置点(例如中途)删除某些内容感到困惑。
我的功能:
void retrieveAndRemove(linkedPtr*hd, int size){
linkedPtr temp = *hd;
if (hd == NULL){
printf("List is empty!");
}
while( temp != NULL){
if (temp->status == IN_RESTAURANT && temp->size == size){
//HERE is where I am stuck, how do i now re-arrange the que
//Such that the node gets removed and the next node is linked
free(temp);
return;
}
temp = temp->next;
}
}
答案 0 :(得分:1)
当您需要从链接列表中间删除节点时,您需要跟踪上一个节点。这将允许您重置链接列表中的链接。
开始状态:
Node to be removed
|
v
+-------+ +-------+ +-------+
| node1 | -- next --> | node2 | -- next --> | node3 |
+-------+ +-------+ +-------+
结束状态:
+-------+ +-------+
| node1 | -- next --> | node3 |
+-------+ +-------+
这是你的功能的修订版本应该有用。
// This wont work for the case when the head needs to be removed.
// void retrieveAndRemove(linkedPtr*hd, int size) {
void retrieveAndRemove(linkedPtr** hd, int size) {
linkedPtr prev = **hd;
linkedPtr cur = prev;
if (hd == NULL){
printf("List is empty!");
return;
}
// Take care of the case where the item to be removed is at the head.
if ( cur->status == IN_RESTAURANT && cur->size == size) {
*hd = cur->next;
free(cur);
}
// Take care of the case where the item to be removed is in the middle.
while( cur != NULL) {
if (cur->status == IN_RESTAURANT && cur->size == size){
// Fix the links.
prev->next = cur->next;
free(cur);
return;
}
prev = cur;
cur = cur->next;
}
}