ACHIYAMA BLOG

Microsoft製品に関する備忘録

C言語でキューを表現

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct cell {
    double num;
    struct cell *next;
};

int main(void) {
    struct cell *listhead = NULL;
    struct cell *listtail = NULL;
    struct cell *p, *q;
    char str[128];

    while (1) {
        printf("操作を選択してください (enq/deq/end) ==> ");
        scanf("%s", str);

        if (strcmp(str, "enq") == 0) {
            p = (struct cell *)malloc(sizeof(struct cell));

            printf("追加する値を入力してください ==> ");
            scanf("%lf", &(p->num));

            p->next = NULL;

            if (listhead == NULL) {
                listhead = listtail = p;

            } else {
                listtail->next = p;
                listtail = p;

            }

            p = listhead;
            while (p != NULL) {
                printf("->%f", p->num);
                p = p->next;

            }

            printf("\n");

        } else if (strcmp(str, "deq") == 0) {
            if (listhead == NULL) {
                printf("キューにデータがありません。\nプログラムを終了します。\n");
                break;

            } else {
                p = listhead;
                listhead = listhead->next;

                printf("%fを削除しました。\n", p->num);
                free(p);

                p = listhead;
                while (p != NULL) {
                    printf("->%f", p->num);
                    p = p->next;

                }

                printf("\n");

            }

        } else if (strcmp(str, "end") == 0) {
            printf("プログラムを終了します。\n");

            p = listhead;
            while (p != NULL) {
                q = p->next;
                free(p);
                p = q;

            }

            break;

        }

    }

    return 0;
}