リンクリストで練習をしていますが、問題が発生しました。リンクされたリストは尾部ですので、ルートノードの1番上の要素を削除します。 I Do notいずれの場合もルートノードを削除します。コードは次のとおりです。リンクリストルートの後にノードを削除
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)
は、あなたがしたい、顧客2その後、依頼された場合他の人が述べたようになど
:
はもう少しコンパクト版です"おそらく' current = root-> next'と 'previous = root'であなたのトラバーサルを開始することは検討する価値があります。ただ言って。これは、 'root'が最初にNULLのために適切にテストされていると仮定します(決して決して言わないでください)。そしてあなたの制限を受けて、私はなぜこのコードで 'どこにでもfree(root);'が存在する理由を知りたいと思っています。 – WhozCraig
ありがとうございます。その理由は次のとおりです.if(前の== NULL){ current = current-> next; 空き(ルート)。 } '私のコードには、削除機能がクラッシュすることなく削除できなかったということがあります –
ええと...別の間違ったことを防ぐために明らかに間違ったことをやっているあなたの狡猾な計画は、Baldrickにとって価値があります。 –