-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
108 lines (90 loc) · 2.36 KB
/
list.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*Created by Omri Kaisari on 05/08/2020.*/
#include <stdlib.h>
#include "list.h"
struct node_t {
void *data;
ListNode next;
};
List list_create() {
ListNode head = (ListNode) malloc(sizeof(struct node_t));
head->next = NULL;
head->data = NULL;
return head;
}
ListNode list_create_list_node(void *data, size_t dataSize) {
ListNode node = (ListNode) malloc(sizeof(struct node_t));
int i;
node->data = malloc(dataSize);
for (i = 0; i < dataSize; i++) {
char current = *((char *) data + i);
*((char *) node->data + i) = current;
}
return node;
}
void list_node_destroy(ListNode node, DestroyFunction destroy) {
if (node == NULL)
return;
if (node->data != NULL) {
if (destroy != NULL)
destroy(node->data);
else
free(node->data);
}
free(node);
}
void list_destroy(List list, DestroyFunction destroy) {
ListNode current = list;
ListNode next;
if (list == NULL)
return;
while (current->next != NULL) {
next = current->next;
list_node_destroy(current, destroy);
current = next;
}
list_node_destroy(current, destroy);
}
size_t list_size(List list) {
int size = 0;
ListNode current = list;
if (list == NULL)
return size;
while (current->next != NULL) {
size++;
current = current->next;
}
return size;
}
void list_insert_node_at_end(List list, void *newData, size_t dataSize) {
ListNode newNode = list_create_list_node(newData, dataSize);
ListNode temp = list;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = NULL;
}
void *list_get_data_element_at_index(List list, int i) {
/*the first element is at index 1 ,returns the original Data element*/
int j = 0;
ListNode current = list;
while (j < i) {
current = current->next;
j++;
}
return current->data;
}
size_t list_get_size_of() {
return sizeof(struct node_t);
}
void *list_find_element(List list, const void *element, Equals compereFunction) {
ListNode current = list;
while (current != NULL) {
if (current->data != NULL) {
if (compereFunction(element, current->data) == 0)
return current->data;
}
current = current->next;
}
return NULL;
}