読者です 読者をやめる 読者になる 読者になる

yaotti's diary

QiitaやKobito、Qiita:Teamを作っています。Software is Eating the World

Cでqueue

添削してもらいました:
yaotti's
gist: 87671 — Gist

ちょっとCを書きたくなったので書いてみた.
いくつかwarningが出るが,原因がわからない.

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

/* queue structure */
typedef struct {
    struct atom_t *head;
    struct atom_t *tail;
} queue_t;

/* structure inside queue like atoms of a list */
typedef struct atom_t{
    int num;
    struct atom *next;
} atom_t;


queue_t * newQ(queue_t * q);
void displayQ(queue_t *q);
void enqueue(queue_t *q, int i);
int dequeue(queue_t *q);

int main()
{
    queue_t *q = (queue_t *)malloc(sizeof(queue_t));
    q = newQ(q);

    /* test */
    displayQ(q);
    enqueue(q, 1);
    displayQ(q);
    enqueue(q, 2);
    displayQ(q);
    enqueue(q, 3);
    displayQ(q);
    dequeue(q);
    displayQ(q);
    dequeue(q);
    displayQ(q);
    dequeue(q);
    displayQ(q);
    dequeue(q);
    displayQ(q);

    free(q);
    return 0;
}

/* make queue having only 0 */
queue_t * newQ(queue_t * q)
{
    atom_t * new = (atom_t *)malloc(sizeof(atom_t));
    new->next = NULL;
    new->num = 0;
    q->head = q->tail = new;
    return q;
}

/* show content of the queue */
void displayQ(queue_t *q)
{
    atom_t * tmp = q->head;
    while (tmp!=q->tail) {
        printf("%d ", tmp->num);
        tmp = tmp->next;        /* warning */
    }
    printf("%d ", tmp->num);
    printf("\n");
    free(tmp);                  /* is it necessary? */
}

/* enqueue an integer value */
void enqueue(queue_t *q, int i)
{
    atom_t *new = (atom_t *)malloc(sizeof(atom_t));
    new->num = i;
    new->next = NULL;
    q->tail->next = new;        /* warning */
    q->tail = new;

}

/* dequeue a value and return that */
int dequeue(queue_t *q)
{
    int retval;
    if (q->head->next!=NULL) {
        retval = q->head->num;
        q->head = q->head->next; /* warning */
    }else {                     /* queue is empty */
        retval = 0;
        q->head = q->tail;
        q->head->num = 0;
    }
    return q->head->num;
}