day06 c语言 单链表查找

c语言

单链表

单链表查找

#include<stdio.h>
#include<stdlib.h>

struct Book
{
    char title[128];
    char author[40];
    struct Book *next;
};

void get(struct Book *book)
{
    printf("请输入书名:\n");
    scanf("%s",book->title);
    printf("请输入作者:\n");
    scanf("%s",book->author);

}
void add(struct Book **library)
{
    struct Book *book;
    static struct Book *tail;

    book = (struct Book *)malloc(sizeof(struct Book));
    if( book == NULL)
    {
        printf("分配内存不足!\n");
        exit(0);
    }
    get(book);
    if(*library != NULL)
    {
        tail ->next = book;
        book ->next = NULL;
    }
    else
    {
        *library = book;
        book->next = NULL;

    }
    tail = book;
}
void  print(struct Book *library)
{
    struct Book *book;
    int count = 1;
    book = library;
    while (book !=NULL)
    {
        printf("Book%d\n",count);
        printf("书名:%s\n",book->title);
        printf("作者:%s\n",book->author);
        book = book->next;
        count++;
    }
}
struct Book *search(struct Book *library, char *target)
{
    struct Book *book;

    book = library;
    while(book != NULL)
    {

        if(!strcmp(book->title,target)||!strcmp(book->author,target))
        {
            break;
        }
        book = book->next;
    }
    return book;
};
void printBook(struct Book *book)
{
    printf("书名:%s\n",book->title);
    printf("作者:%s\n",book->author);
}
void release(struct Book **library)
{
    struct Book *nsdd;
    while(*library != NULL)
    {
        nsdd = *library;
        *library = (*library)->next;
        free(nsdd);

    }
}

int main (void)
{

    struct Book *library = NULL;
    struct Book *book = NULL;
    char input[128];
    char ch;
    while(1)
    {
        printf("请问是否需要录入书籍信息?(Y\N)");
        do
        {
            ch = getchar();

        }
        while(ch != 'Y'&&ch !='N');
        if(ch =='Y')
        {
            add(&library);
        }
        else
        {
            break;
        }
    }
    printf("是否需要打印图书信息(Y\N)?");
    do
    {
        ch = getchar();
    }
    while(ch !='Y'&&ch != 'N');
    if(ch == 'Y')
    {
        print(library);
    }
    printf("\n请输入书名或作者:\n");
    scanf("%s",input);
    book = search(library,input);
    if( book ==NULL)
    {
        printf("lz没找到\n");
    }
    else
    {
        do
        {
            printf("已经找到你tm要的书\n");
            printBook(book);
        }
        while((book = search(book->next,input)) != NULL) ;

    }

    release(&library);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追寻远方的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值