
C言語のキューを教えて!
こういった悩みにお答えします.
本記事の信頼性
- リアルタイムシステムの研究歴12年.
- 東大教員の時に,英語でOSの授業.
- 2012年9月~2013年8月にアメリカのノースカロライナ大学チャペルヒル校コンピュータサイエンス学部(2021年の世界大学学術ランキングで20位)で客員研究員として勤務.C言語でリアルタイムLinuxの研究開発.
- プログラミング歴15年以上,習得している言語: C/C++,Solidity/Vyper,Java,Python,Ruby,HTML/CSS/JS/PHP,MATLAB,Assembler (x64,ARM).
- 東大教員の時に,C++言語で開発した「LLVMコンパイラの拡張」,C言語で開発した独自のリアルタイムOS「Mcube Kernel」をGitHubにオープンソースとして公開.
こういった私から学べます.
キュー
キューとは,データを先入れ先出し(First In First Out)で保持するデータ構造です.
キューにデータに入れることをエンキュー(enqueue),データをキューから取り出すことをデキュー(dequeue)と呼びます.
他のデータ構造を知りたいあなたはこちらからどうぞ.
-
-
【C言語】連結リストとは【片方向リスト,双方向リスト,双方向循環リスト】
こういった悩みにお答えします. こういった私から学べます. 目次1 連結リスト2 C言語のリスト2.1 片方向リスト2.2 双方向リスト2.3 双方向循環リスト3 リストの実例:Linuxカーネル3. ...
続きを見る
-
-
【C言語】スタックとは【x86のアセンブリ言語で解説】
こういった悩みにお答えします. こういった私から学べます. 目次1 スタック2 C言語のスタック3 x86の命令セットアーキテクチャでスタックを操作するpush/pop命令4 まとめ スタック スタッ ...
続きを見る
C言語のキュー
C言語のシンプルなキューのコードは以下になります.
QUEUE_SIZE分のデータを格納できます.
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 |
/* * Author: Hiroyuki Chishiro * License: 2-Clause BSD */ #include <stdio.h> #define QUEUE_SIZE 128 struct queue { int data[QUEUE_SIZE]; size_t index; size_t num; }; void init(struct queue *q) { size_t i; for (i = 0; i < QUEUE_SIZE; i++) { q->data[i] = 0; } q->index = q->num = 0; } void print(struct queue *q) { size_t i; printf("print(): "); for (i = q->index; i < q->index + q->num; i++) { printf("%d ", q->data[i % QUEUE_SIZE]); } printf("\n"); } void increment(struct queue *q) { q->index++; if (q->index == QUEUE_SIZE) { q->index = 0; } } int enqueue(struct queue *q, int data) { if (q->num >= QUEUE_SIZE) { fprintf(stderr, "Error: queue is full.\n"); return 1; } q->data[(q->index + q->num) % QUEUE_SIZE] = data; q->num++; return 0; } int dequeue(struct queue *q, int *data) { if (q->num == 0) { fprintf(stderr, "Error: queue is empty.\n"); return 1; } *data = q->data[q->index % QUEUE_SIZE]; increment(q); q->num--; return 0; } void clear(struct queue *q) { init(q); } int main(void) { struct queue queue; size_t i; int data; init(&queue); for (i = 1; i <= 5; i++) { enqueue(&queue, i); print(&queue); } for (i = 1; i <= 3; i++) { if (dequeue(&queue, &data) == 0) { printf("data = %d\n", data); } print(&queue); } clear(&queue); print(&queue); return 0; } |
実行結果は以下になります.
データをFIFOで操作していることがわかります.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ gcc queue.c $ a.out print(): 1 print(): 1 2 print(): 1 2 3 print(): 1 2 3 4 print(): 1 2 3 4 5 data = 1 print(): 2 3 4 5 data = 2 print(): 3 4 5 data = 3 print(): 4 5 print(): |
C言語の優先度キューの例「二項ヒープ」
キューの応用として,データを優先度付きで管理する優先度キューが挙げられます.
優先度キューでは,主に最高優先度のデータをキューから取り除くため,リアルタイムOSにおけるタスクのキューで利用されています.
優先度キューにより,リアルタイム性を保証しつつタスクをデッドラインまでに実行することが可能になります.
リアルタイムOSに使われる技術であるリアルタイムシステムを知りたいあなたはこちらからどうぞ.
-
-
元東大教員から学ぶリアルタイムシステム
こういった私から学べます. リアルタイムシステムとは,決められた時間(デッドライン)までに処理を完了しなければならない性質をもつシステムのことです. リアルタイムシステムは,ロボット,自動車や航空機な ...
続きを見る
本記事では,優先度キューの例として二項ヒープを紹介します.
二項ヒープの特徴は以下になります.
- 二分ヒープとよく似たデータ構造であるが,二項ヒープは2つのヒープを素早くマージする操作をサポート
- 特殊な木構造「二項木」を利用して実現
- マージ可能な抽象データ型ヒープの実装
C言語の二項ヒープのコードは以下になります.
とても複雑なので,時間をかけて読みましょう.難しかったら読み飛ばしても構いません.
二項ヒープのコードで実装されている主な関数は以下になります.
- enqueue_bheap_queue関数:二項ヒープにノードをエンキュー
- dequeue_bheap_queue関数:二項ヒープからノードをデキュー
- pick_next_value関数:二項ヒープから最高優先度ノードの値(struct value型)を取得
- print_bheap関数:二項ヒープのノードを表示
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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
/* * Author: Hiroyuki Chishiro * License: 2-Clause BSD */ #include <stdio.h> #include <stdbool.h> #include <limits.h> #define QUEUE_SIZE 128 #define NOT_IN_BHEAP ULONG_MAX #ifdef PDEBUG #define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args) #else #define PDEBUG(fmt, args...) #endif struct value { unsigned long id; unsigned long priority; int value; struct bheap_node *node; }; struct bheap_node { unsigned long node_id; struct bheap_node *parent; struct bheap_node *next; struct bheap_node *child; unsigned long degree; struct value *value; }; struct bheap_queue { unsigned long id; struct bheap_node *head; struct bheap_node *min; }; void print_bheap(struct bheap_queue *bq, struct bheap_node *h) { static int nr_tabs = 0; int i; if (!h) { printf("NULL\n"); for (i = 0; i < nr_tabs; i++) { printf("\t"); } return; } printf("node_id(%lu)id(%lu)deg(%lu)->", h->node_id, h->value->id, h->degree); nr_tabs++; print_bheap(bq, h->child); nr_tabs--; print_bheap(bq, h->next); } bool empty_bheap(struct bheap_queue *bq) { return !(bq->head) && !(bq->min); } bool is_higher_priority(struct value *a, struct value *b) { /* Smaller priority has higher priority. * In the tie-breaking rule, smaller id has higher priority. */ return a->priority < b->priority || ((a->priority == b->priority) && (a->id < b->id)); } void link_bheap(struct bheap_node *root, struct bheap_node *child) { child->parent = root; child->next = root->child; root->child = child; root->degree++; } struct bheap_node *merge_bheap(struct bheap_node *p, struct bheap_node *q) { struct bheap_node *head = NULL; struct bheap_node **pos = &head; while (p && q) { if (p->degree < q->degree) { *pos = p; p = p->next; } else { *pos = q; q = q->next; } pos = &(*pos)->next; } if (p) { *pos = p; } else { *pos = q; } return head; } struct bheap_node *reverse_bheap(struct bheap_node *h) { struct bheap_node *tail = NULL; struct bheap_node *next; if (!h) { return h; } h->parent = NULL; while (h->next) { next = h->next; h->next = tail; tail = h; h = next; h->parent = NULL; } h->next = tail; return h; } void min_bheap(struct bheap_queue *bq, struct bheap_node **prev, struct bheap_node **node) { struct bheap_node *_prev, *cur; *prev = NULL; if (!bq->head) { *node = NULL; return; } *node = bq->head; _prev = bq->head; cur = bq->head->next; while (cur) { PDEBUG("min_bheap(): cur->value->id = %lu (*node)->value->id = %lu\n", cur->value->id, (*node)->value->id); if (is_higher_priority(cur->value, (*node)->value)) { *node = cur; *prev = _prev; } _prev = cur; cur = cur->next; } } void union_bheap(struct bheap_queue *bq, struct bheap_node *h2) { struct bheap_node *h1; struct bheap_node *prev, *x, *next; if (!h2) { return; } h1 = bq->head; if (!h1) { bq->head = h2; return; } h1 = merge_bheap(h1, h2); prev = NULL; x = h1; next = x->next; while (next) { if ((x->degree != next->degree) || (next->next && (next->next->degree == x->degree))) { /* nothing to do, advance. */ prev = x; x = next; } else if (is_higher_priority(x->value, next->value)) { /* x becomes the root of next. */ PDEBUG("union_bheap(): x->value->id = %lu priority = %lu becomes the root of next.\n", x->value->id, x->value->priority); PDEBUG("union_bheap(): next->value->id = %lu priority = %lu\n", next->value->id, next->value->priority); x->next = next->next; link_bheap(x, next); } else { /* next becomes the root of x. */ if (prev) { prev->next = next; } else { h1 = next; } link_bheap(next, x); x = next; } next = x->next; } bq->head = h1; } struct bheap_node *min_bheap_extract(struct bheap_queue *bq) { struct bheap_node *prev, *node; min_bheap(bq, &prev, &node); if (!node) { return NULL; } if (prev) { prev->next = node->next; } else { bq->head = node->next; } union_bheap(bq, reverse_bheap(node->child)); return node; } void insert_bheap(struct bheap_queue *bq, struct bheap_node *node) { struct bheap_node *min; PDEBUG("insert_bheap(): node = %lx node->value->id = %lu\n", (unsigned long) node, node->value->id); node->child = NULL; node->parent = NULL; node->next = NULL; node->degree = 0; if (bq->min && is_higher_priority(node->value, bq->min->value)) { /* swap min cache */ min = bq->min; min->child = NULL; min->parent = NULL; min->next = NULL; min->degree = 0; union_bheap(bq, min); bq->min = node; } else { union_bheap(bq, node); } } void min_bheap_uncache(struct bheap_queue *bq) { struct bheap_node *min; if (bq->min) { min = bq->min; bq->min = NULL; insert_bheap(bq, min); } } /* merge addition into target */ void union_bheap_uncache(struct bheap_queue *target, struct bheap_queue *addition) { /* first insert any cached minima, if necessary */ min_bheap_uncache(target); min_bheap_uncache(addition); union_bheap(target, addition->head); /* this is a destructive merge */ addition->head = NULL; } void decrease_bheap(struct bheap_queue *bq, struct bheap_node *node) { struct bheap_node *parent; void *tmp; unsigned long node_id; if (!node) { return; } if (bq->min != node) { /* bubble up */ parent = node->parent; while (parent && is_higher_priority(node->value, parent->value)) { /* swap parent and node */ tmp = parent->value; node_id = parent->node_id; parent->value = node->value; parent->node_id = node->node_id; node->value = (struct value *) tmp; node->node_id = node_id; /* swap value->node */ tmp = node->value->node; node->value->node = parent->value->node; parent->value->node = (struct bheap_node *) tmp; /* step up */ node = parent; parent = node->parent; } } } void delete_bheap(struct bheap_queue *bq, struct bheap_node *node) { struct bheap_node *parent, *prev, *pos; void *tmp; unsigned long node_id; if (!node) { return; } PDEBUG("delete_bheap(): node->id = %lu\n", node->node_id); if (bq->min != node) { /* bubble up */ parent = node->parent; while (parent) { /* swap parent and node */ tmp = parent->value; node_id = parent->node_id; parent->value = node->value; parent->node_id = node->node_id; node->value = (struct value *) tmp; node->node_id = node_id; /* swap value->node */ tmp = node->value->node; node->value->node = parent->value->node; parent->value->node = (struct bheap_node *) tmp; /* step up */ node = parent; parent = node->parent; } /* now delete: * first find prev */ prev = NULL; pos = bq->head; while (pos != node) { prev = pos; pos = pos->next; } /* we have prev, now remove node */ if (prev) { prev->next = node->next; } else { bq->head = node->next; } union_bheap(bq, reverse_bheap(node->child)); } else { bq->min = NULL; } node->degree = NOT_IN_BHEAP; } void enqueue_bheap_queue(struct bheap_queue *bq, struct value *value_node) { insert_bheap(bq, value_node->node); } void dequeue_bheap_queue(struct bheap_queue *bq, struct value *value_node) { delete_bheap(bq, value_node->node); } struct value *pick_next_value(struct bheap_queue *bh_queue) { struct value *value_node = NULL; struct bheap_node *bn; if (!empty_bheap(bh_queue)) { struct bheap_node *prev; min_bheap(bh_queue, &prev, &bn); value_node = bn->value; } return value_node; } void init_bheap_node(struct bheap_node *h, struct value *value_node) { h->parent = NULL; h->next = NULL; h->child = NULL; h->degree = NOT_IN_BHEAP; h->value = value_node; h->node_id = value_node->id; } void init_value_node(struct value *value_node, unsigned long id, struct bheap_node *h) { value_node->id = id; value_node->priority = id; value_node->value = id; value_node->node = h; } void init_bheap(struct bheap_queue *bh_queue, struct bheap_node bh_nodes[QUEUE_SIZE], struct value value_nodes[QUEUE_SIZE]) { int i; bh_queue->head = bh_queue->min = NULL; for (i = 0; i < QUEUE_SIZE; i++) { init_value_node(&value_nodes[i], i + 1, &bh_nodes[i]); init_bheap_node(&bh_nodes[i], &value_nodes[i]); value_nodes[i].node = &bh_nodes[i]; } } int main(void) { struct bheap_queue bh_queue; struct bheap_node bh_nodes[QUEUE_SIZE]; struct value value_nodes[QUEUE_SIZE]; struct value *value; init_bheap(&bh_queue, bh_nodes, value_nodes); printf("print_bheap():\n"); print_bheap(&bh_queue, bh_queue.head); enqueue_bheap_queue(&bh_queue, &value_nodes[0]); printf("print_bheap():\n"); print_bheap(&bh_queue, bh_queue.head); enqueue_bheap_queue(&bh_queue, &value_nodes[2]); printf("print_bheap():\n"); print_bheap(&bh_queue, bh_queue.head); enqueue_bheap_queue(&bh_queue, &value_nodes[1]); printf("print_bheap():\n"); print_bheap(&bh_queue, bh_queue.head); dequeue_bheap_queue(&bh_queue, &value_nodes[2]); printf("print_bheap():\n"); print_bheap(&bh_queue, bh_queue.head); value = pick_next_value(&bh_queue); printf("pick_next_value(): value->id = %lu\n", value->id); printf("print_bheap():\n"); print_bheap(&bh_queue, bh_queue.head); return 0; } |
実行結果は以下になります.
enqueue_bheap_queue関数でノードをエンキューしたり,dequeue_bheap_queue関数でノードをデキューしたりした場合に,二項ヒープの木構造がどのように変化するのかをprint_bheap関数で確認しています.
最高優先度ノードの値を取得したい場合は,pick_next_value関数を利用します.
ここで,pick_next_value関数では,ノードをデキューしないことに注意して下さい.
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 |
$ gcc bheap.c $ a.out print_bheap(): NULL print_bheap(): node_id(1)id(1)deg(0)->NULL NULL print_bheap(): node_id(1)id(1)deg(1)->node_id(3)id(3)deg(0)->NULL NULL NULL print_bheap(): node_id(2)id(2)deg(0)->NULL node_id(1)id(1)deg(1)->node_id(3)id(3)deg(0)->NULL NULL NULL print_bheap(): node_id(1)id(1)deg(1)->node_id(2)id(2)deg(0)->NULL NULL NULL pick_next_value(): value->id = 1 print_bheap(): node_id(1)id(1)deg(1)->node_id(2)id(2)deg(0)->NULL NULL NULL |
まとめ
C言語のキューとして,シンプルなキューと,優先度キューの二項ヒープを紹介しました.
二項ヒープのコードは複雑なので,コードを修正したらどのように結果が変化するのかを試してみましょう.
他のキューとしてリングバッファ(リングキュー)が挙げられます.
C言語のリングバッファのコードを知りたいあなたはこちらからどうぞ.
-
-
【C言語】おすすめのリングバッファのライブラリ
こういった悩みにお答えします. こういった私から学べます. 目次1 embedded-resources:おすすめのリングバッファのライブラリ2 embedded-resourcesのC言語のリングバ ...
続きを見る
C言語を独学で習得することは難しいです.
私にC言語の無料相談をしたいあなたは,公式LINE「ChishiroのC言語」の友だち追加をお願い致します.
独学が難しいあなたは,元東大教員がおすすめするC言語を学べるオンラインプログラミングスクール5社で自分に合うスクールを見つけましょう.後悔はさせません!