首页 > 代码库 > 02 单链表

02 单链表

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

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

int linkList_init(linkList **list)
{
    (*list) = (linkList *)malloc(sizeof(linkList));

    if (*list == NULL)
    {
        return -1; 
    }

    (*list)->next = NULL;

    return 0;
}

int linkList_add(linkList *list, int data)
{
    if (list == NULL)
    {
        return -1; 
    }

    linkList *node = (linkList *)malloc(sizeof(linkList));
    if (node == NULL)
    {
        return -2; 
    }

    node->data =http://www.mamicode.com/ data;
    node->next = list->next;
    list->next = node;

    return 0;
}

linkList *linkList_del(linkList *list)
{
    if (list == NULL || list->next == NULL)
    {
        return NULL; 
    }

    linkList *node = list->next;

    list->next = node->next;

    return node;
}

int linkList_display(linkList *list)
{
    if (list == NULL)
    {
        return -1; 
    }

    linkList *node = list->next;

    while (node != NULL)
    {
        printf("%d-", node->data); 
        node = node->next;
    }

    printf("\n");

    return 0;
}

int main()
{
    int i = 0;
    linkList *list = NULL;
    linkList *node = NULL;

    linkList_init(&list);

    for (i = 0; i < 10; i++)
    {
        linkList_add(list, i); 
    }

    linkList_display(list);

    node = linkList_del(list);
    if (node != NULL)
    {
        printf("node:%d\n", node->data); 
        free(node);
    }

    linkList_display(list);

    return 0;
}

 

02 单链表