函数快查------https://fishc.com.cn/thread-66397-1-1.html
单链表
头插入举例
#include<stdio.h>
struct Book
{
char title[128];
char author[40];
struct Book *next;//指针域
};//结构体
void getInput(struct Book *book)
{
printf("请输入书名:");
scanf("%s",book->title);
printf("请输入作者:");
scanf("%s",book->author);
}//定义getinput
void addBook(struct Book **library)
{
struct Book *book,*temp;//temp为临时地址,存放插入节点后面的信息域
book = (struct Book *)malloc(sizeof(struct Book));
//申请一块内存空间
if(book == NULL){
printf("内存分配失败\n");
exit(1);
}
getInput(book);//传入函数*book的地址
if(*library != NULL)
{
temp = *library;
*library = book;
book->next = temp;
//插入
}
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",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;
//头指针
int ch;
while(1)
{
printf("请问是否需要录入书籍信息(Y/N)\n");
do{
ch = getchar();
} while(ch != 'Y' && ch != 'N');//如果不是Y或N就不停循环
if(ch == 'Y')
{
addBook(&library);
}
else
{
break;
}
}
printf("请问是否需要打印书籍信息(Y/N)\n");
do
{
ch = getchar();
} while(ch != 'Y' &&ch != 'N');
if(ch == 'Y')
{
printLibrary(library);
}
releaseLibrary(&library);//释放library
return 0;
}
尾插入,只需将addbook的头插入替换成尾插入即可
void addBook(struct Book **library)
{
struct Book *book;
static struct Book *tail;
//定义指向尾部的静态指针变量
book = (struct Book *)malloc(sizeof(struct Book));
//申请一块内存空间
if(book == NULL){
printf("内存分配失败\n");
exit(1);
}
getInput(book);//传入函数*book的地址
if(*library != NULL)
{
tail->next = book;
book->next = NULL;
//插入数据
}
else
{
*library = book;
book->next = NULL;
}
tail = book;
}