C语言实现简单单链表

#include <stdio.h>                                                                                                                                                                                               
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

void init_node(struct node **p)
{
    *p = malloc(sizeof(struct node));
    if(*p == NULL)
    {
        printf("malloc error!");
        exit(0);
    }
    (*p)->next = NULL;
}

void create_head_chain(struct node *phead)
{
    int i;
    struct node *tmp;
    for(i=0;i<10;i++)
    {
        init_node(&tmp);
        tmp->data = i+1;
        tmp->next = phead->next;
        phead->next = tmp;
    }
}

void create_end_chain(struct node *phead)
{
    int i;
    struct node *tmp;
    for(i=0;i<10;i++)
    {
        init_node(&tmp);
        tmp->data = i+1;
        phead->next = tmp;
        phead = tmp;
    }
}

void destory_chain(struct node *phead)
{
    struct node *tmp;
    while(phead->next != NULL)
    {
        tmp = phead->next;
        phead->next = tmp->next;
        free(tmp);
    }
    free(phead);
}

void show_chain(struct node *phead)
{
    struct node *tmp;
    for(tmp = phead->next;tmp != NULL;tmp = tmp->next)
        printf("%d ",tmp->data);
    printf("\n");
}

int main()
{
    struct node *phead = NULL;
    init_node(&phead);
    /*create_head_chain(phead);*/
    create_end_chain(phead);
    show_chain(phead);
    destory_chain(phead);
    show_chain(phead);
}

 

posted @ 2021-03-27 10:41  TO_ZG  阅读(122)  评论(0编辑  收藏  举报