我在鏈接列表中練習,我遇到了一個問題。鏈表是尾巴,所以我想刪除位於根節點上方的第一個元素。我不要在任何情況下想刪除根節點。該代碼是:鏈接列表刪除節點後根
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值得:( –