-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdll.c
58 lines (51 loc) · 1.12 KB
/
dll.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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* HW: write insert_sorted, edit to have head & tail ptrs in a struct */
typedef struct dllnode_t dllnode;
struct dllnode_t {
int val;
dllnode *next;
dllnode *prev;
};
void dll_verify(const dllnode *head) {
assert(head->prev == NULL);
while ((head = head->next)) {
assert(head->prev->next == head);
}
}
void dll_insert_head(dllnode **head, int val) {
dllnode *tmp = malloc(sizeof(dllnode));
tmp->val = val;
tmp->prev = NULL; /* one place insert_sorted changes */
if (*head)
(*head)->prev = tmp;
tmp->next = *head;
*head = tmp;
}
int dll_delete_first(dllnode **head, int val) {
dllnode *tmp;
dllnode *prev;
for (tmp = *head; tmp->val != val; tmp = tmp->next)
;
if (!tmp) return 0;
if (tmp->prev) {
prev = tmp->prev;
tmp->prev->next = tmp->next;
} else {
prev = NULL;
*head = tmp->next;
}
if (tmp->next)
tmp->next->prev = prev;
free(tmp);
return 1;
}
int main() {
dllnode *head = NULL;
dll_insert_head(&head, 5);
dll_insert_head(&head, 3);
dll_insert_head(&head, 1);
dll_verify(head);
return 0;
}