小甲鱼 P45 单链表1---头插法
单链表包含两个域:信息域、指针域
- 信息域:存放链表节点的内容
- 指针域:指向下一个 和它一样的节点
结束:直到最后一个节点的指针域为NULL
头指针:指向第一个节点
连接:链表通过指针进行连接的
单链表声明
struct Book
{
//信息域
char title[128];
char author[40];
//指针域(指向下一个和它一样的节点)
struct Book *next;
}
在单链表中插入元素
头插法:
首先在堆里面申请一块新的内存空间,用来存放这个节点。自己填充它的信息域,把head指针原来的指向擦除,然后把head指针指向新节点,把新节点的指针域指向原来第一个元素的地址。
在下面代码中,因为addBook()和releaseLibrary()函数传进去的参数是指针的地址,所以参数类型为指针的指针 **
#include <stdio.h>
#include <stdlib.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 releaseLibrary(struct Book **library);
void getInput(struct Book *book)
{
printf("请输入书名:");
scanf("%s", book->title);
printf("请输入作者:");
scanf("%s", book->author);
}
void addBook(struct Book **library)//参数library(head指针)是head指针的值,两层解引用
{
//**library参数:指向head指针,head指针的值,头结点,是一个地址
//下面的*library头指针:是原来的第一个结构体的地址
/* **library参数 = &library头指针
*library头指针 = &原来的第一个结构体
原来的第一个结构体 = NULL
*/
struct Book *book, *temp;//临时变量temp
//在堆里面申请新的节点
book = (struct Book *)malloc(sizeof(struct Book));
if (book == NULL)
{
printf("内存分配失败了!\n");
exit(1);
}
//为新节点填充信息域的内容
getInput(book);
if (*library != NULL)
{
//把新的节点插入到链表的头部
temp = *library;//保存原来head指针指向的地址
*library = book;//把head指针指向新节点
book->next = temp;//把新节点的指针域指向原来head指针指向的地址
}
else//如果为NULL,空的单链表
{
*library = book;
book->next = NULL;
}
}
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", book->author);
putchar('\n');
book = book->next;//指向下一个节点
count++;
}
}
void releaseLibrary(struct Book **library)//参数library(head指针)是head指针的值,两层解引用
{
struct Book *temp;//临时变量
while (*library != NULL)//直到library头指针指向NULL
{
temp = *library;
*library = (*library)->next;
free(temp);
//如果先释放头指针,那么就没有意义了
//library = library->next;
//free(library);
}
}
int main(void)
{
//头指针 head, NULL, 空的单链表
struct Book *library = NULL;
int ch;
while (1)
{
printf("请问是否需要录入书籍信息(Y/N):");
do
{
ch = getchar();
}while(ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
addBook(&library);
}
else
{
break;//退出死循环
}
}
printf("请问是否需要打印图书信息(Y/N):");
do
{
ch = getchar();
}while(ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
printLibrary(library);
}
releaseLibrary(&library);
return 0;
}
总结:(例子:原来是NULL,现在插入一个)不懂的看指针的指针
addBook()函数:
(参数)**library = &头指针library
*头指针library = &原来第一个结构体
原来第一个结构体=它的内容 title author next