-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.c
executable file
·99 lines (82 loc) · 2.11 KB
/
linked_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
#include "linked_list.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void linked_list_node_free(struct linked_list_node* node)
{
assert(node != NULL);
if (node->data != NULL)
free(node->data);
free(node);
}
void linked_list_initialize(struct linked_list* list, size_t size)
{
list->head = NULL;
list->current = NULL;
list->tail = NULL;
list->size = size;
}
void linked_list_add(struct linked_list* list, void* data)
{
assert(list->size != 0);
struct linked_list_node* node = (struct linked_list_node*)malloc(sizeof(struct linked_list_node));
if (node == NULL) {
fprintf(stderr, "error allocating memory for linked list\n");
exit(1);
}
node->data = (void*)malloc(list->size);
if (node->data == NULL) {
fprintf(stderr, "error allocating memory for linked list node\n");
exit(1);
}
memcpy(node->data, data, list->size);
node->next = NULL;
if (list->tail != NULL)
list->tail->next = node;
list->tail = node;
if (list->head == NULL) {
list->head = node;
list->current = list->head;
}
}
void linked_list_delete(struct linked_list* list, struct linked_list_node* node)
{
struct linked_list_node* current_node = list->head;
struct linked_list_node* previous_node = NULL;
while (current_node != NULL) {
if (current_node == node) {
if (current_node == list->head)
list->head = list->head->next;
else
previous_node->next = current_node->next;
linked_list_node_free(current_node);
break;
}
previous_node = current_node;
current_node = current_node->next;
}
}
struct linked_list_node* linked_list_next(struct linked_list* list)
{
if (list->current != NULL) {
struct linked_list_node* node = list->current;
list->current = list->current->next;
return node;
}
return NULL;
}
void linked_list_reset(struct linked_list* list)
{
list->current = list->head;
}
void linked_list_free(struct linked_list* list)
{
struct linked_list_node* current_node = list->head;
while (current_node != NULL) {
struct linked_list_node* next_node = current_node->next;
free(current_node);
current_node = next_node;
}
}