-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.c
54 lines (46 loc) · 1.27 KB
/
linkedlist.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
bool LinkedListDestroy(LinkedList *node, bool recursive, void deconstructor(void *ptr)) {
if (node == NULL) {
#ifndef NDEBUG
fprintf(stderr, "%s: NULL pointer is provided. Ignored!\n", __FUNCTION_NAME__);
#endif
return false;
}
// if deconstructor is not provided, use free from stdlib
if (deconstructor == NULL) {
deconstructor = free;
}
LinkedList *cur = node, *next;
do {
next = cur->next;
// free a block for something
if (cur->ptr != NULL) {
deconstructor(cur->ptr);
}
// free a block for node
free(cur);
} while (recursive && (cur = next) != NULL);
return true;
}
LinkedList *LinkedListAppend(LinkedList *parentNode, void *ptr) {
LinkedList *node = calloc(1, sizeof(LinkedList));
// initialize node
node->next = NULL;
node->ptr = ptr;
node->length = 1;
/*
* if parent node is provided, this is child node.
* pattern 1) 1->2 => 1->me->2
* pattern 2) 1 => 1->me
*/
if (parentNode != NULL) {
node->next = parentNode->next;
parentNode->next = node;
++parentNode->length;
}
// if parent node is not provided, this is parent node
return node;
}
LinkedList *LinkedListCreate(void *ptr) { return LinkedListAppend(NULL, ptr); }