C 语言实例7——单链表 的搜索

// 单链表的搜索
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

// 单链表声明
struct Book
{
   //信息域
	char title[128];
	char author[40];
	//指针域
   struct Book * next;
};


void getInput(struct Book *book);
void addBook(struct Book **library) ;
void printlibrary(struct Book *library);
void relsaselibrary(struct Book **library);
struct Book  *searchBook(struct Book *library,char *target);
void printBook(struct Book *book);



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

void addBook(struct Book **library)  //参数library (head指针)是head指针的值。
{
  struct  Book  *book;
  static struct  Book  *tail;   //指向链表尾部
  // 在堆里面申请新的节点
  book =(struct Book *)malloc(sizeof(struct Book));
  if(book==NULL)
  {
    printf("内存分配失败");
	exit(1);
  }

  // 为新节点填充信息域内容
  getInput(book);

  if(*library != NULL)
  {
	  // 插入数据
	  tail->next = book;  
	  book->next=NULL;   
  
  }
  else   // 如果为NULL 空的单链表
  {
    *library = book;
	book->next=NULL;  
  }
  tail =book;
}

void printlibrary(struct Book *library)
{
   struct Book *book;
   int count =1;

   book = library;
   while(book != NULL)
   {
     printf("Book%d: " ,count);
	 printf("书名:%s",book->title);
	 printf("作者:%s\n",book->author);
	
	 book = book->next;
	 count++;
   
   }

}

void relsaselibrary(struct Book **library)
{
    struct Book *temp; // 临时变量

	while(*library !=NULL)    //直到library头指针指向NULL
	{
	    temp = *library;
		*library =(*library)->next;
		free(temp); 
	}
}

struct Book  *searchBook(struct Book *library,char *target)
{
  struct Book *book;
  book = library;
  while(book != NULL)
  {
	  if(!strcmp(book->author,target)|| !strcmp(book->title,target))
	  {
	    break;
	  }
	  book = book->next;
  }
  return book;   //返回节点的指针
}

void printBook(struct Book *book)
{
  printf("书名:%s",book->title);
  printf("作者:%s",book->author);
}

int main()
{
  
	  struct Book *library = NULL;
	  struct Book *book;
	  int ch; 
	  char input[128];
      while(1)
	  {
	      printf("请问是否需要录入书籍信息(Y/N):");
		  do
		  {
		       ch = getchar();
		 
		  }
	      while( ch !='Y' && ch!='N');

	      if(ch == 'Y')
		  {
	          addBook(&library);
		  }
	      else
		  {
	          break;
		  }
         
	  }
	   printlibrary(library);

	   printf("请输入书名或作者:");
	   scanf("%s",input);
	   book =searchBook(library,input);
	   if(book ==NULL)
	   {
	     printf("没有找到相关书籍\n");
	   }
	   else
	   {
	    do 
		{
		  printf("已找到符合书籍...\n");
		  printBook(book);
		}
		while((book=searchBook(book->next,input))!= NULL);
	   }
       relsaselibrary(&library);
	   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值