码迷,mamicode.com
首页 > 编程语言 > 详细

C语言接口与实现学习笔记——链表

时间:2015-08-08 16:10:11      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

实现一个链表的一系列接口,体会了指针的用法

 

list.h

#ifndef LIST_INCLUDE
#define LIST_INCLUDE

#define T List_T
typedef struct T *T;
struct T
{
    T rest;
    void *first;
};

extern T List_append(T list, T tail);
extern T List_copy(T list);
extern T List_list(void *x, ...);
extern T List_pop(T list, void **x);
extern T List_push(T list, void *x);
extern T List_reverse(T list);
extern int List_length(T list);
extern void List_free(T *list);
extern void List_map(T list, void apply(void **x, void *cl), void *cl);
extern void **List_toArray(T list, void *end);

#undef T
#endif // LIST_INCLUDE

list.c

#include <stdarg.h>
#include <stddef.h>
#include "assert.h"
#include "mem.h"
#include "list.h"

#define T List_T

T List_push(T list, void *x)
{
    T p;

    NEW(p);
    p->first = x;
    p->rest = list;
    return p;
}

T List_list(void *x, ...)
{
    va_list ap;
    T list, *p = &list;

    va_start(ap, x);
    for(; x; x = va_arg(ap, void*))
    {
        NEW(*p);
        (*p)->first = x;
        p = &(*p)->rest;
    }
    *p = NULL;
    va_end(ap);
    return list;
}

T List_append(T list, T tail)
{
    T *p = &list;

    while(*p)
    {
        p = &(*p)->rest;
    }
    *p = tail;
    return list;
}

T List_copy(T list)
{
    T head, *p = &head;

    for(; list; list = list->rest)
    {
        NEW(*p);
        (*p)->first = list->first;
        p = &(*p)->rest;
    }
    *p = NULL;
    return head;
}

T List_pop(T list, void **x)
{
    if(list)
    {
        T head = list->rest;
        if(x)
        {
            *x = list->first;
        }
        FREE(list);
        return head;
    }
    else
    {
        return list;
    }
}

T List_reverse(T list)
{
    T head = NULL, next;

    for(; list; list = next)
    {
        next = list->rest;
        list->rest = head;
        head = list;
    }

    return head;
}

int List_length(T list)
{
    int n;

    for(n = 0; list; list = list->rest)
    {
        n++;
    }

    return n;
}

void List_free(T *list)
{
    T next;

    assert(list);
    for(; *list; *list = next)
    {
        next = (*list)->rest;
        FREE(*list);
    }
}

void List_map(T list, void apply(void **x, void *cl), void *cl)
{
    assert(apply);
    for(; list; list = list->rest)
    {
        apply(&list->first, cl);
    }
}

void **List_toArray(T list, void *end)
{
    int i, n = List_length(list);
    void **array = ALLOC((n+1)*sizeof(*array));

    for(i = 0; i < n; ++i)
    {
        array[i] = list->first;
        list = list->rest;
    }

    array[i] = end;
    return array;
}

 

C语言接口与实现学习笔记——链表

标签:

原文地址:http://www.cnblogs.com/ygw0616/p/4713251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!