修改宠物俱乐部程序,把所有同名的宠物都存储在同一个节点。当用户选择查找宠物时,程序应咨询用户该宠物的名字,然后列出该名字的所有宠物(及其种类)

/修改宠物俱乐部程序,把所有同名的宠物都存储在同一个节点。当用户选择查找宠物时,程序应咨询用户该宠物的名字,然后列出该名字的所有宠物(及其种类)/

include <stdio.h>

include <stdlib.h>

include <string.h>

typedef struct Pet
{
char name[50];
char species[50];
struct Pet *next;
} Pet;

typedef struct PetClub
{
Pet *head;
} PetClub;

PetClub *create_pet_club()
{
PetClub *club = (PetClub *)malloc(sizeof(PetClub));
club->head = NULL;
return club;
}

void add_pet(PetClub *club, const char *name, const char *species)
{
Pet *new_pet = (Pet *)malloc(sizeof(Pet));
strcpy(new_pet->name, name);
strcpy(new_pet->species, species);
new_pet->next = NULL;

if (club->head == NULL)
{
    club->head = new_pet;
}
else
{
    Pet *current = club->head;
    Pet *prev = NULL;

    while (current != NULL && strcmp(current->name, name) < 0)
    {
        prev = current;
        current = current->next;
    }

    if (prev != NULL && strcmp(prev->name, name) == 0)
    {
        while (prev->next != NULL)
        {
            prev = prev->next;
        }
        prev->next = new_pet;
    }
    else if (prev == NULL)
    {
        new_pet->next = club->head;
        club->head = new_pet;
    }
    else
    {
        new_pet->next = current;
        prev->next = new_pet;
    }
}

}

void find_pets(PetClub *club, const char *name)
{
Pet *current = club->head;
int found = 0;

while (current != NULL)
{
    if (strcmp(current->name, name) == 0)
    {
        printf("宠物名: %s, 种类: %s\n", current->name, current->species);
        found = 1;
    }
    current = current->next;
}

if (!found)
{
    printf("未找到该名字的宠物。\n");
}

}

void free_pet_club(PetClub *club)
{
Pet *current = club->head;
while (current != NULL)
{
Pet *temp = current;
current = current->next;
free(temp);
}
free(club);
}
int main(void)
{
PetClub *club = create_pet_club();
add_pet(club, "Buddy", "Dog");
add_pet(club, "Buddy", "Cat");
add_pet(club, "Max", "Dog");
char pet_name[50];
printf("请输入要查找的宠物名字: ");
scanf("%s", pet_name);
find_pets(club, pet_name);
free_pet_club(club);
return 0;
}

posted on 2024-08-11 23:22  wessf  阅读(1)  评论(0编辑  收藏  举报