单链表之头插法

来源:互联网 发布:java base64库 编辑:程序博客网 时间:2024/06/08 18:05

单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象)
指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。

头插法

#include <stdio.h>#include <stdlib.h>//单链表   :// head --> 信息域(节点内容)|指针域 (指向下一节点)--> 信息域(节点内容)|指针域 (指向下一节点)--> ...-->NULL//头插法 struct Book{    char title[128];    char author[40];    struct Book *next;};void getInput(struct Book *book){    scanf("%s", book -> title);    scanf("%s", book -> author);}void addBook(struct Book **library){    struct Book *book, *tmp;    book = (struct Book *) malloc(sizeof(struct Book));    if(book == NULL) exit(0);    getInput(book);    if(*library != NULL)    {        tmp = *library;        *library = book;        book -> next = tmp;    }    else    {        //空节点         *library = book;        book -> next = NULL;    }}void printLibrary(struct Book *library){    struct Book *book;    int count = 1;    book = library;    while(book != NULL)    {        printf("\n");        printf("第%d本书:\n", count);        printf("书名:%s\n", book -> title);        printf("作者:%s\n", book -> author);        printf("---------\n");        book = book -> next;        count++;    }} void releaseLibrary(struct Book **library)//释放内存 {    struct Book *tmp;     while(*library != NULL){        tmp = *library;        *library = (*library) -> next;        free(tmp);    }}int main(){    struct Book *library = NULL;   //head     addBook(&library);    addBook(&library);    //addBook(&library);    printLibrary(library);    releaseLibrary(&library);    return 0;}
**输入:**AAABBBCCCDDD**输出:**第1本书:书名:CCC作者:CCC---------第2本书:书名:AAA作者:AAA---------

图解

这里写图片描述

———————————

图解:

这里写图片描述