我在链接列表中练习,我遇到了一个问题。链表是尾巴,所以我想删除位于根节点上方的第一个元素。我不要在任何情况下想删除根节点。该代码是:链接列表删除节点后根
struct goods{
char* section;
char* pname;
int value;
int customer_num;
int cash;
struct goods* next;
};
void delete_goods(int customer_num,struct goods* root)
{
struct goods *current=root;
struct goods *previous=NULL;
while(current!=NULL){
if(current->customer_num == customer_num){
if (previous==NULL){
current=current->next;
free(root);
}
else {
previous->next=current->next;
free(current);
current=previous->next;
}
}
else{
previous=current;
current=current->next;
}
}
}
int main(){
root = malloc(sizeof(struct goods));
root ->next=NULL;
printf("give the number of starting customers\n");
scanf("%d",&customers);
inform_list(customers);// adds element to list
else if(r=='r'&&customers!=0){
printf("removing...\n");
delete_goods(customers,root);
customers-=1;
printf("customers:\t%d\n",customers);
print();
}
}
我没有张贴整个代码(它包括一些功能添加元素,为您提供方便,如果你喜欢,我可以做链接列表,我需要的方式来解决我的删除功能所以我满足上述需求 下面列表中的一个示例输出:customers: 2 customer: 2 item value: 32 product name: asdasd customer: 1 item value: 43 product name: sdsad customer: 0 item value: 0 product name: (null)
我需要的是我的删除功能删除客户1,如果问那么顾客2等
如果你不想删除根节点“在任何情况下“可能在'current = root-> next'和'previous = root'开始遍历值得考虑。只是说。假设'root'首先被正确地测试了NULL(永远不会说永远不会)。并且,考虑到你的限制,我想知道为什么'free(root);'存在于*代码中的任何位置*。 – WhozCraig
感谢Whoz。该陈述的原因如果(前一个== NULL){current} = current-> next; free(root); }'存在我的代码是,我不能删除没有使我的删除功能崩溃 –
是的...我担心你做一个明显错误的事情,以防止发生另一个错误的事情的狡猾计划是Baldrick值得:( –