Skip to content

Instantly share code, notes, and snippets.

@LightBells
Forked from riku1314/キュー
Last active July 15, 2020 15:10
Show Gist options
  • Save LightBells/477157ccb775afe0fd39780903f06dfe to your computer and use it in GitHub Desktop.
Save LightBells/477157ccb775afe0fd39780903f06dfe to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define ID "s1270096"
#define NAME "Hikaru Takahashi"
//----------------------------------
typedef enum { OK, EMPTY, FULL } result_t;
// キューの要素(ノード)を表す構造体
typedef struct _node {
struct _node * next_p; // リスト内の次の要素(ノード)へのポインタ
int data;
} node_t;
// キューを表す構造体
typedef struct _queue{
node_t * head_p; // 先頭のノードへのポインタ
node_t * tail_p; // 最後のノードへのポインタ
} queue_t;
//----------------------------------
// キューの初期化
void que_init(queue_t * que_p) {
que_p->head_p = NULL;
que_p->tail_p = NULL;
} // end of que_init;
//----------------------------------
// キューへの追加
result_t enqueue(queue_t* que_p, int data) {
node_t* node_p;
node_p = (node_t*)malloc(sizeof(node_t)); // ノードの割付.malloc関数を使う.
if (node_p == NULL) return FULL;
node_p->next_p = que_p -> head_p;
node_p->data = data;
if (que_p->tail_p == NULL) {
que_p -> head_p = node_p; // head_pが割り当てられたノードを示すようにする.
que_p -> tail_p = node_p; // tail_pが割り当てられたノードを示すようにする.
} else {
que_p -> tail_p -> next_p = node_p;; // キューの最後の要素(ノード)が割り当てられたノードを示すようにする.
que_p -> tail_p = node_p; // tail_pが割り当てられたノードを示すようにする.
}
return OK;
} // end of enqueue;
//----------------------------------
// キューからのデータの取り出し
// 取り出したデータは*dataに設定する
result_t dequeue(queue_t * que_p, int* data) {
if (que_p->tail_p == NULL) return EMPTY;
*data = que_p -> head_p -> data ;// 取り出したデータの設定 → data
que_p->head_p = que_p -> head_p -> next_p;
if (que_p->head_p == NULL) return EMPTY;
return OK;
} // end of dequeue;
//----------------------------------
// キューの内容を表示
void print_que(queue_t * que_p) {
node_t* np;
printf("queue: ");
for (np = que_p->head_p ; np = que_p -> tail_p ; np = np->next_p) { // キューの各要素を走査.npが各要素を示す.
printf("%d ", np->data);
}
printf("\n");
} // end of print_que
//----------------------------------
int main() {
queue_t que;
result_t cc;
int data;
printf("%s %s\n\n", ID, NAME);
que_init(&que);
cc = dequeue(&que, &data);
if (cc == EMPTY) printf("ERR: queue is empty\n");
cc = enqueue(&que, 3);
cc = enqueue(&que, 5);
cc = enqueue(&que, 2);
print_que(&que);
cc = dequeue(&que, &data); printf("%d\n", data);
cc = dequeue(&que, &data); printf("%d\n", data);
print_que(&que);
cc = dequeue(&que, &data); printf("%d\n", data);
printf("\n%s %s\n\n", ID, NAME);
return 0;
} // end of main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment