ex32 List impl improvements

This commit is contained in:
Dan Buch 2016-04-17 12:25:52 -04:00
parent 508ac1a5d1
commit 015288d5b6
No known key found for this signature in database
GPG Key ID: FAEF12936DD3E3EC
2 changed files with 29 additions and 2 deletions

View File

@ -8,6 +8,8 @@ List *List_create()
void List_destroy(List *list)
{
List_validate(list);
LIST_FOREACH(list, first, next, cur) {
if(cur->prev) {
free(cur->prev);
@ -21,6 +23,8 @@ void List_destroy(List *list)
void List_clear(List *list)
{
List_validate(list);
LIST_FOREACH(list, first, next, cur) {
free(cur->value);
}
@ -29,13 +33,24 @@ void List_clear(List *list)
void List_clear_destroy(List *list)
{
List_clear(list);
List_destroy(list);
List_validate(list);
LIST_FOREACH(list, first, next, cur) {
free(cur->value);
if(cur->prev) {
free(cur->prev);
}
}
free(list->last);
free(list);
}
void List_push(List *list, void *value)
{
List_validate(list);
ListNode *node = calloc(1, sizeof(ListNode));
check_mem(node);
@ -58,12 +73,16 @@ error:
void *List_pop(List *list)
{
List_validate(list);
ListNode *node = list->last;
return node != NULL ? List_remove(list, node) : NULL;
}
void List_unshift(List *list, void *value)
{
List_validate(list);
ListNode *node = calloc(1, sizeof(ListNode));
check_mem(node);
@ -86,12 +105,16 @@ error:
void *List_shift(List *list)
{
List_validate(list);
ListNode *node = list->first;
return node != NULL ? List_remove(list, node) : NULL;
}
void *List_remove(List *list, ListNode *node)
{
List_validate(list);
void *result = NULL;
check(list->first && list->last, "List is empty.");

View File

@ -2,6 +2,7 @@
#define lcthw_List_h
#include <stdlib.h>
#include <assert.h>
struct ListNode;
@ -34,6 +35,9 @@ void *List_shift(List *list);
void *List_remove(List *list, ListNode *node);
#define List_validate(A) (assert(A != NULL && List_count(A) > -1 &&\
(List_count(A) > 0 && List_first(A) != NULL) && "invalid *List"))
#define LIST_FOREACH(L, S, M, V) ListNode *_node = NULL;\
ListNode *V = NULL;\
for(V = _node = L->S; _node != NULL; V = _node = _node->M)