首页 > 编程语言 > 详细

C语言实现简单单链表

时间:2021-03-27 12:27:35      阅读:21      评论:0      收藏:0      [点我收藏+]
#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);
}

 

C语言实现简单单链表

原文:https://www.cnblogs.com/zgen1/p/14585107.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!