马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
struct Book //初始化结构体
{
char tittle[128];
char author[24];
struct Book *next;
};
getInput(struct Book* book)
{
printf("请输入书名:\n");
scanf("%s", book->tittle);
printf("请输入作者:\n");
scanf("%s", book->author);
}
addBook(struct Book** head) //向结构体中插入节点
{
struct Book *book;
static struct Book *tail;=============================问题:即使一开始空链表执行else,但还是不明白tail是如何定位到链表尾部的,
book = (struct Book *)malloc(sizeof(struct Book));//创建新节点
if(book==NULL)
{
printf("节点创建失败,退出程序!!!");
exit(1);
}
getInput(book); //录入书的内容
if(*head!=NULL)
{
tail->next = book;
book->next = NULL;
}
else
{
*head = book;
book->next= NULL;
}
}
void Print (struct Book* head) //打印链表内容
{
struct Book *book;
int count = 1; //计数君count
book = head;
while(book!=NULL)
{
printf("第%d本书\n", count);
printf("书名:%s\n",book->tittle);
printf("作者:%s\n",book->author);
book = book->next;
count++;
}
}
Free(struct Book** head) //每次释放的都是首个节点
{
struct Book *temp;
while(*head!=NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
int main()
{
struct Book *head = NULL;
char ch;
while (1)
{
printf("请问是否需要录入书籍信息(y / n): ");
do
{
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y')
{
addBook(&head); //传递的参数是library变量本身的地址
}
else
{
break;
}
}
printf("是否输出图书信息(y / n): ");
do
{
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y')
{
Print(head); //打印library指向的链表信息
}
Free(head); //释放library指向的链表内存
return 0;
}
|