-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.c
115 lines (100 loc) · 2.44 KB
/
DoublyLinkedList.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
#include "DoublyLinkedList.h"
struct node {
unsigned char ch;
struct node *prev;
struct node *next;
};
static struct node *create_node(unsigned char ch) {
struct node *new_node = malloc(sizeof(struct node));
new_node->ch = ch;
new_node->prev = NULL;
new_node->next = NULL;
return new_node;
}
void insert_start(list *l, unsigned char ch) {
struct node *new_node = create_node(ch);
if (l->first == NULL) {
l->first = new_node;
l->last = l->first;
} else {
new_node->next = l->first;
l->first->prev = new_node;
l->first = new_node;
}
}
void insert_end(list *l, unsigned char ch) {
struct node *new_node = create_node(ch);
if (l->last == NULL) {
l->last = new_node;
l->first = l->last;
} else {
l->last->next = new_node;
new_node->prev = l->last;
l->last = new_node;
}
}
int find_index(list *l, unsigned char ch) {
int index = 0;
struct node *p = l->first;
while (p != NULL && p->ch != ch) {
++index;
p = p->next;
}
return index;
}
void delete(list *l, unsigned char ch) {
struct node *p = l->first;
while (p != NULL && p->ch != ch)
p = p->next;
if (p == NULL)
return;
if (p == l->first) {
if (p->next == NULL) {
l->first = NULL;
l->last = NULL;
} else {
l->first = p->next;
l->first->prev = NULL;
}
} else if (p == l->last) {
if (p->prev == NULL) {
l->first = NULL;
l->last = NULL;
} else {
l->last = p->prev;
l->last->next = NULL;
}
} else {
p->prev->next = p->next;
p->next->prev = p->prev;
}
free(p);
}
unsigned char delete_index(list *l, int index) {
struct node *p = l->first;
while (index-- && p != NULL)
p = p->next;
unsigned char ch = p->ch;
if (p == l->first) {
if (p->next == NULL) {
l->first = NULL;
l->last = NULL;
} else {
l->first = p->next;
l->first->prev = NULL;
}
} else if (p == l->last) {
if (p->prev == NULL) {
l->first = NULL;
l->last = NULL;
} else {
l->last = p->prev;
l->last->next = NULL;
}
} else {
p->prev->next = p->next;
p->next->prev = p->prev;
}
free(p);
return ch;
}