0
這是我的代碼,我不知道它有什麼問題。當我使用鍵盤輸入「刪除」列表中的項目時,它會更改其他項目的名稱。另外,當我輸入不在列表中的名稱時,它將刪除項目。如何解決它?C中的鏈接列表刪除
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct list
{
char name[20];
int age;
char gender[10];
struct list *next;
};
void main(void)
{
struct list *HEAD = NULL;
struct list *temp,*current, *trav;
struct list *prev;
char choice;
while(1)
{
clrscr();
printf("MENU\n");
printf("A) ADD\n");
printf("B) DISPLAY\n");
printf("C) DELETE\n");
printf("X) EXIT\n");
scanf("%c", &choice);
switch(toupper(choice))
{
case 'A':
temp= (struct list*)malloc(sizeof(struct list));
temp->next=NULL;
printf("Fill-Up the following:\n");
printf("Name:");
fflush(stdin);
gets(temp->name);
printf("Age:");
fflush(stdin);
scanf("%d",&temp->age);
printf("Gender:");
fflush(stdin);
gets(temp->gender);
if(HEAD == NULL)
{
HEAD = temp;
}
else if(HEAD!=NULL)
{
for(trav=HEAD; trav->next != NULL; trav= trav->next);
trav->next=temp;
}
else
{
printf("Not Enough Memory!\n");
}
break;
case 'B':
if(HEAD==NULL)
{
printf("Linked List is Empty!\n");
getch();
}
else{
for(trav=HEAD; trav != NULL; trav=trav->next)
{
printf("\nName: %s\n", trav->name);
printf("Age: %d\n", trav->age);
printf("Gender: %s\n\n", trav->gender);
}
getch();
}
break;
case 'C' :
if(HEAD==NULL)
{
printf("No item to be delete. List is Empty!\n");
getch();
}
else {
printf("Enter The Name of the item you want to Delete: ");
fflush(stdin);
gets(temp->name);
current=HEAD;
if(strcmp(temp->name,current->name)== 0)
{
HEAD=HEAD->next;
free(current);
printf("Item has been successfully deleted from the list.\n");
getch();
}
else
{
for(prev=HEAD,trav=HEAD->next; strcmp(trav->name,temp->name)!=0 ; trav=trav->next,prev=prev->next);
if(trav==NULL)
{
printf("Name: %s not found!", temp->name);
getch();
}
else{
prev->next=trav->next;
free(trav);
printf("Item has been successfully deleted from the list.\n");
getch();
}
}
}
break;
case 'X':
if(HEAD!=NULL){free(HEAD); }
if(trav!=NULL){ free(trav); }
if(temp!=NULL){ free(temp); }
exit(1);
break;
}
}
}
什麼不爲每項任務編寫單獨的函數,如添加,刪除,打印? – Shravan40