简单单链表的 创建 打印 和 释放

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


typedef struct node {
    int val;
    struct node *next;
}Node;


void free_list(Node *list)
{
    Node *tmp = NULL;
    while(list)
    {
        tmp = list->next;
        free(list);
        list = tmp;
    }
}

void print_list(Node *list)
{
    while(list)
    {
        printf("%u ", list->val);
        list = list->next;
    }
    printf("\n");
}

Node *create_list(void)
{
    int len, i;
    Node *list = NULL;
    Node **pcur = NULL;
    Node *tmp = NULL;

    printf("Please input length and elements:");
    scanf("%u", &len);
    pcur = &list;
    for(i=0; i<len; i++)
    {
        tmp = (Node *)malloc(sizeof(Node));
        if(NULL == tmp)
        {
            free_list(list);
            printf("malloc error!!\n");
            return NULL;
        }
        memset(tmp, 0, sizeof(Node));
        scanf("%u", &tmp->val);

        *pcur = tmp;
        pcur = &(*pcur)->next;
    }

    return list;
}

int main(int argc, char *argv[])
{
    Node *list = NULL;

    list = create_list();

    print_list(list);

    print_list(list);

    free_list(list);

    return 0;
}

发布了27 篇原创文章 · 获赞 2 · 访问量 4618

猜你喜欢

转载自blog.csdn.net/xqjcool/article/details/52074378