-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrock_queue.c
More file actions
executable file
·95 lines (70 loc) · 1.87 KB
/
Copy pathrock_queue.c
File metadata and controls
executable file
·95 lines (70 loc) · 1.87 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rock_queue.h"
/*
* find the middle queue element if the queue has odd number of elements
* or the first element of the queue's second part otherwise
*/
rock_queue_t *rock_queue_middle(rock_queue_t *queue)
{
rock_queue_t *middle, *next;
middle = rock_queue_head(queue);
if (middle == rock_queue_last(queue)) return middle;
next = rock_queue_head(queue);
for (;;)
{
middle = rock_queue_next(middle);
next = rock_queue_next(next);
if (next == rock_queue_last(queue)) return middle;
next = rock_queue_next(next);
if (next == rock_queue_last(queue)) return middle;
}
}
/* the stable insertion sort */
void rock_queue_sort(rock_queue_t *queue, int (*cmp)(const rock_queue_t *, const rock_queue_t *))
{
rock_queue_t *q, *prev, *next;
q = rock_queue_head(queue);
if (q == rock_queue_last(queue)) return;
for (q = rock_queue_next(q); q != rock_queue_sentinel(queue); q = next)
{
prev = rock_queue_prev(q);
next = rock_queue_next(q);
rock_queue_remove(q);
do {
if (cmp(prev, q) <= 0) break;
prev = rock_queue_prev(prev);
} while (prev != rock_queue_sentinel(queue));
rock_queue_insert_after(prev, q);
}
}
#if 0 //debug
typedef struct rock_test rock_test_t;
struct rock_test
{
int data;
rock_queue_t q;
};
int main(void)
{
int i;
rock_queue_t h, *p;
struct rock_test *tmp;
rock_queue_init(&h);
for (i = 0; i < 10; ++i)
{
tmp = (struct rock_test*)calloc(1, sizeof(struct rock_test));
tmp->data = i;
rock_queue_insert_head(&h, &tmp->q);
}
p = &h;
while ((p = rock_queue_next(p)) != &h)
{
tmp = rock_queue_data(p, rock_test_t, q);
printf("%d ", tmp->data);
}
printf("\n");
return 0;
}
#endif