-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.c
More file actions
75 lines (67 loc) · 1.44 KB
/
linked_list.c
File metadata and controls
75 lines (67 loc) · 1.44 KB
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
#include <stdlib.h>
#include <stdio.h>
typedef struct Node{
void* element;
struct Node* next;
}Node;
Node* createList() {
Node* node = (Node*) malloc(sizeof(Node));
if (node == NULL) {
fprintf(stderr, "Out of memory.\n");
exit(-1);
}
node->element = NULL;
node->next = NULL;
return node;
}
int size(Node* list) {
if (list->element == NULL) {
return 0;
}
int sum = 1;
while(list->next != NULL) {
sum++;
list = list->next;
}
return sum;
}
void append(Node* list, void* el) {
if (el == NULL) {
fprintf(stderr, "Cannot append NULL element\n");
return;
}
if (size(list) == 0) {
list->element = el;
return;
}
while (list->next != NULL) {
list = list->next;
}
list->next = (Node*) malloc(sizeof(Node));
if (list->next == NULL) {
fprintf(stderr, "Out of memory.\n");
exit(-1);
}
list->next->element = el;
list->next->next = NULL;
}
void* getElement(Node* list, int index) {
int length = size(list);
if (index >= length || index < 0) {
fprintf(stderr, "Index out of bounds: %d\n", index);
return NULL;
}
for (int i = 0; i < index; i++) {
list = list->next;
}
return list->element;
}
void freeList(Node* list){
if(list == NULL) {
return;
}
if(list->next != NULL) {
freeList(list->next);
}
free(list);
}