-
Notifications
You must be signed in to change notification settings - Fork 0
/
List.c
121 lines (105 loc) · 1.82 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdlib.h>
#include "List.h"
List *ListCreate(void *data)
{
if (data == NULL)
return NULL;
List *root = (List *)malloc(sizeof(List));
if (root == NULL)
return NULL;
root->next = root->prev = root;
root->data = data;
return root;
}
size_t ListSize(List *root)
{
if (root == NULL)
return 0UL;
size_t size = 0UL;
List *temp = root;
do {
size++;
temp = temp->next;
} while (temp != root);
return size;
}
int ListInsert(List *pred, void *data)
{
if (pred == NULL || data == NULL)
return -1;
List *node = ListCreate(data);
List *next = pred->next;
pred->next = node;
node->next = next;
node->prev = pred;
next->prev = node;
return 0;
}
int ListRemove(List **_link)
{
if (*_link == NULL)
return -1;
if (*_link == (*_link)->next) {
free(*_link);
*_link == NULL;
return 0;
}
List *next = (*_link)->next;
List *prev = (*_link)->prev;
free(*_link);
*_link == NULL;
prev->next = next;
next->prev = prev;
return 0;
}
int ListPushBack(List **_root, void *data)
{
if (data == NULL)
return -1;
if (*_root == NULL) {
*_root = ListCreate(data);
return 0;
}
return ListInsert((*_root)->prev, data);
}
int ListPushFront(List **_root, void *data)
{
if (data == NULL)
return -1;
if (*_root == NULL) {
*_root = ListCreate(data);
return 0;
}
ListInsert((*_root)->prev, data);
*_root = (*_root)->prev;
return 0;
}
int ListPopBack(List **_root)
{
return ListRemove(&(*_root)->prev);
}
int ListPopFront(List **_root)
{
List *next = (*_root)->next;
int res = ListRemove(_root);
*_root = next;
return res;
}
int ListDelete(List **_root)
{
if (*_root == NULL)
return -1;
if (*_root == (*_root)->next) {
free(*_root);
*_root = NULL;
return 0;
}
List *temp = *_root;
do {
List *next = temp->next;
free(temp);
temp = next;
} while (temp != *_root);
*_root = NULL;
return 0;
}