本文主要是介绍C.Interface.And.Implementations—list(单链表)的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
单链表的原理不在赘述!
通过优美的源代码进行理解其中的道理!
======================list.h=========================
#ifndef LIST_INCLUDED
#define LIST_INCLUDED#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.c===========================
#include <stdarg.h>
#include <stddef.h>
#include "assert.h"
#include "mem.h"
#include "list.h"#define T List_T//functions
T List_push(T list, void *x){T p;NEW(p);p->first = x;p->rest = list;retunr 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.Interface.And.Implementations—list(单链表)的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!