>我只是想从链表中删除一个节点,似乎遇到了麻烦。我想知道是否有人可以看看可能出了什么问题?谢谢!
struct ets {
struct node *equip_head;
struct node *member_head;
struct node *loan_head;
const char *equip_fname;
const char *member_fname;
const char *loan_fname;
};
struct node {
void *data; /* Accepts all data, yay */
struct node *next;
};
BOOLEAN deleteMember(struct ets *ets, char MemberID[]) {
struct node *current = ets->member_head;
struct node *tmpNode = current;
struct member_data *member_data = NULL;
while (current != NULL) {
member_data = current->data;
if (strcmp(member_data->MemberID, MemberID) == 0) {
tmpNode = current;
current = current->next;
free(tmpNode->data);
free(tmpNode);
return TRUE;
}
current = current->next;
}
return FALSE;
}
您不会从列表中删除节点。您可以执行此操作以从列表中删除节点:
BOOLEAN deleteMember(struct ets *ets, char MemberID[]) {
struct node *current = ets->member_head;
struct node *prev=NULL;
struct member_data *member_data = NULL;
while(current != NULL) {
member_data = current->data;
if(strcmp(member_data->MemberID, MemberID) == 0) {
if(prev==NULL) // removing 1st node
ets->member_head=current->next;
else
prev->next=current->next; // removing current node from list
free(current->data);
free(current);
return TRUE;
}
prev = current;
current = current->next;
}
return FALSE;
}
因为你有一个链表,你删除算法是坏的。这是您目前正在做的事情:
- 找到要删除的成员。好。你有
node-1 -> node -> node+1
- 删除成员。为什么不呢。但是您的列表将变得
node-1 -> unallocated node
并且无法找到下一个节点
相反,您应该测试下一个节点是否具有正确的 id,以具有类似以下内容的内容:prev_node(current)
-> node_to_delete -> next_node'
然后你可以做:
tmpNode = current->next;
current->next = tmpNode->next; /* ok for the chaining */
free(tmpNode->data); /* deletion will be ok */
free(tmpNode);
当然,对第一个和最后一个节点进行了特殊管理...
编辑:阿里已经给出了答案。我留下这个作为对OP算法为什么被破坏的评论