-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.c
89 lines (65 loc) · 1.29 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdlib.h>
#include "linkedlist.h"
LNKLIST *lnklist_init() {
LNKLIST *head = (LNKLIST*)malloc(sizeof(LNKLIST));
if(head == NULL)
return NULL;
head->prev = head;
head->next = head;
head->val = NULL;
return head;
}
int lnklist_insert_after(LNKLIST *node, void *val) {
if(node == NULL)
return -1;
LNKLIST *new_node = (LNKLIST*)malloc(sizeof(LNKLIST));
if(new_node == NULL)
return -2;
node->next->prev = new_node;
new_node->next = node->next;
node->next = new_node;
new_node->prev = node;
new_node->val = val;
return 0;
}
void *lnklist_delete(LNKLIST *node) {
void *res;
if(node == NULL)
return NULL;
node->prev->next = node->next;
node->next->prev = node->prev;
res = node->val;
free(node);
return res;
}
int lnklist_destroy(LNKLIST *head, void (*destroy_data)(void *)) {
LNKLIST *node;
LNKLIST *tmp;
if(head == NULL)
return -1;
node = head->next;
while(node != head) {
tmp = node->next;
if(node->val != NULL)
if(destroy_data == NULL)
free(node->val);
else
destroy_data(node->val);
free(node);
node = tmp;
}
free(head);
return 0;
}
LNKLIST *lnklist_find_n(LNKLIST *head, int n) {
LNKLIST *e = head->next;
int i = 1;
while(e != head && i < n) {
i++;
e = e->next;
}
if(e == head)
return NULL;
else
return e;
}