-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlargest_block.c
82 lines (70 loc) · 1.58 KB
/
largest_block.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
#include <stdint.h>
#include <stdlib.h>
#include "largest_block.h"
const uint32_t NUM_LARGEST = 10;
dl_list insert(uint32_t value, uint32_t data, dl_list list)
{
dl_list_node* curr = list.head, *tail = list.tail;
dl_list_node* new_node = NULL;
// See if we even need to insert
if (list.count >= NUM_LARGEST && tail->value > value)
{
return list;
}
// Build the new node
new_node = (dl_list_node*)malloc(sizeof(*new_node));
new_node->prev = new_node->next = NULL;
new_node->value = value;
new_node->data = data;
/* Do the insertion */
// Special case -- empty list
if (list.count == 0 || !list.head)
{
list.head = list.tail = new_node;
list.count = 1;
return list;
}
// Special case -- insert at head
if (list.head && value > list.head->value)
{
new_node->next = list.head;
list.head->prev = new_node;
list.head = new_node;
++list.count;
}
// Special case -- insert at tail
else if (list.tail && value <= list.tail->value)
{
new_node->prev = list.tail;
list.tail->next = new_node;
list.tail = new_node;
++list.count;
}
// Insert in the middle
else
{
for (curr = list.head; curr && curr != list.tail; curr = curr->next)
{
if (curr->value < value)
{
new_node->prev = curr->prev;
new_node->next = curr;
curr->prev->next = new_node;
curr->prev = new_node;
++list.count;
break;
}
}
}
// Drop smallest if over count
while (list.count > NUM_LARGEST + 1)
{
dl_list_node* dead = list.tail;
dead->prev->next = NULL;
list.tail = dead->prev;
--list.count;
free(dead);
}
// Return the new list
return list;
}