单链表2笔记

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

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

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





void addBook(struct Book** library)
{
	struct Book* book, * temp;


	book = (struct Book*)malloc(sizeof(struct Book));
	if (book == NULL)
	{
		printf("内存分配失败\n");
		exit(1);
	}

	getInput(book);

	if (*library != NULL)
	{
		temp = *library;

		while (temp->next != NULL)
		{
			temp = temp->next;
		}
		temp->next = book;
		book->next = NULL;
	}
	else
	{
		*library = book;
		book->next = NULL;
	}
}

void printlibrary(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\n", book->author);
		book = book->next;
		count++;
	}


}

void releaselibrary(struct Book* library)
{
	struct Book* temp;
	while (library != NULL)
	{
		temp = library;
		library = library->next;
		free(temp);

	}
}


int main(void)
{
	struct Book* library = NULL;//library事实上就是头指针  
	int ch;

	while (1)
	{
		printf("是否需要录入信息(Y/N):");
		do
		{
			ch = getchar();
		} while (ch != 'Y' && ch != 'N');

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

	printf("是否需要打印图书信息");
	do
	{
		ch = getchar();
	} while (ch != 'Y' && ch != 'N');

	if (ch == 'Y')
	{
		printlibrary(library);

	}

	releaselibrary(library);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值