1215.2——单链表

链表的结点结构
 ┌───┬───┐
 │data|next│
 └───┴───┘
data域--存放结点值的数据域
next域--存放结点的直接后继的地址(位置)的指针域(链域)

实例:从终端输入5个姓名,单链表输出
typedef struct node{

    char * name;

    struct node *next;

}Node;  // 定义一个结构体

 

void myfree(Node * pHead){   //从头指针开始释放

    while (pHead != NULL) {

        Node *ptemp = pHead->next;

        free(pHead->name);

        free(pHead);

        pHead = ptemp;

    }

} //释放申请过的内存

 

int main(int argc, const char * argv[]) {

    Node *phead = NULL;   //定义头指针

    Node *ptail = NULL;   //定义尾指针

    for (int i = 0; i<5; i++) {

        Node *ptemp = (Node*)malloc(1*sizeof(Node));   //申请一个结构体大小的空间

        if (ptemp == NULL) {

            myfree(phead);

            exit(EXIT_FAILURE);

        }    

        printf("请输入姓名:");

        char * name=NULL  //临时存放name

        char c;

        int total =0;  // 用来计数 当前存到第几个

        while (1) {

            c=getchar();

            if (c==' ') {

                break;

            }

            if (name == NULL) {   // 如果第一次存放

                name = (char*)malloc(1*sizeof(char));

                if(name==NULL){

                    free(ptemp);

                    myfree(phead);

                    exit(EXIT_FAILURE);

                }

                

            }else{

                name = (char*)realloc(name,(total+1)*sizeof(char) );

                if (name == NULL) {

                    free(ptemp);

                    myfree(phead);

                    exit(EXIT_FAILURE);

                }

            }

            

            *(name+total)=c;   // 依次存放

            total++;

        }

        

        ptemp->name = name;   //指向临时的name

        ptemp->next = NULL;

        

        if (phead==NULL) {  //如果头指针是空的 头指针尾指针指向第一个

            phead = ptemp;

            ptail = ptemp;

        }else{

            ptail->next = ptemp;  // 衔接之后 尾指针移动

            ptail = ptemp;

        }

    }

    Node * ptemp = phead;  //防止头指针跑,找不到后面的,所以定义临时的

    while (ptemp!=NULL) {

        printf("%s  ",ptemp->name);

        ptemp=ptemp->next;

    }

    myfree(phead);

    return 0;

}

原文地址:https://www.cnblogs.com/damonWq/p/5049463.html