-
Notifications
You must be signed in to change notification settings - Fork 2
/
list.c
123 lines (108 loc) · 2.06 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
122
123
#include "list.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct listnode listnode;
struct listnode {
listnode *prev, *next;
void *data;
};
struct list {
listnode *current;
unsigned size;
};
int listCheck(list *lst);
list *listCreate()
{
list *lst = malloc(sizeof(list));
lst->current = NULL;
lst->size = 0;
return lst;
}
void listFree(list *lst)
{
assert(listCheck(lst));
if(lst->current) {
listnode *start = lst->current;
do {
listnode *next = lst->current->next;
free(lst->current);
lst->current = next;
} while(lst->current != start);
}
free(lst);
}
void listInsert(list *lst, void *data)
{
assert(lst && listCheck(lst));
listnode *node = malloc(sizeof(listnode));
if(lst->current) {
node->next = lst->current;
node->prev = lst->current->prev;
node->prev->next = node;
node->next->prev = node;
if(lst->current->next == lst->current) {
lst->current->next = node;
}
}
else {
node->next = node;
node->prev = node;
}
lst->current = node;
node->data = data;
lst->size++;
}
void listDeleteCurrent(list *lst)
{
assert(lst && lst->current && listCheck(lst));
listnode *next = lst->current->next,
*prev = lst->current->prev;
free(lst->current);
lst->size--;
if(lst->size == 0) {
lst->current = NULL;
}
else {
lst->current = next;
next->prev = prev;
prev->next = next;
}
}
void *listGetCurrent(list *lst)
{
assert(lst && lst->current && listCheck(lst));
return lst->current->data;
}
int listSize(list *lst)
{
assert(lst && listCheck(lst));
return lst->size;
}
void listMoveBack(list *lst)
{
assert(lst && listCheck(lst));
if(lst->current)
lst->current = lst->current->prev;
}
void listMoveForward(list *lst)
{
assert(lst && listCheck(lst));
if(lst->current)
lst->current = lst->current->next;
}
int listCheck(list *lst)
{
if(!lst->current)
return true;
listnode *node = lst->current;
int listsize = lst->size,
i;
for(i = 0; i < listsize; i++, node = node->next) {
if(node != node->next->prev || node != node->prev->next) {
return 0;
}
}
return true;
}