Skip to content

Instantly share code, notes, and snippets.

@yaotti
Forked from kana/yaotti-queue.c
Created March 30, 2009 07:07
Show Gist options
  • Save yaotti/87671 to your computer and use it in GitHub Desktop.
Save yaotti/87671 to your computer and use it in GitHub Desktop.
/* http://d.hatena.ne.jp/yaotti/20090330/1238391711 */
#include <stdio.h>
#include <stdlib.h>
/* structure inside queue like atoms of a list */
typedef struct atom_t{
int num;
struct atom_t *next;
} atom_t;
/* queue structure */
typedef struct {
struct atom_t *head;
struct atom_t *tail;
} queue_t;
atom_t *newAtom(int v);
void deleteAtom(atom_t *a);
queue_t *newQ(void);
void deleteQ(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 = newQ();
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);
deleteQ(q);
return 0;
}
atom_t *newAtom(int v)
{
atom_t *a = (atom_t *)malloc(sizeof(atom_t));
a->num = v;
return a;
}
void deleteAtom(atom_t *a)
{
free(a);
}
queue_t *newQ(void)
{
queue_t *q = (queue_t *)malloc(sizeof(queue_t));
q->head = q->tail = NULL;
return q;
}
void deleteQ(queue_t *q)
{
atom_t *a = q->head;
atom_t *n = q->head;
while (a != NULL) {
n = a->next;
free(a);
a = n;
}
free(q);
}
void displayQ(queue_t *q)
{
atom_t *a = q->head;
printf("[ ");
while (a != NULL) {
printf("%d ", a->num);
a = a->next;
}
printf("]\n");
}
void enqueue(queue_t *q, int i)
{
atom_t *a = newAtom(i);
a->next = NULL;
if (q->tail == NULL) {
q->head = q->tail = a;
} else {
q->tail->next = a;
q->tail = a;
}
}
int dequeue(queue_t *q)
{
int v;
atom_t* a = q->head;
if (a != NULL) {
v = a->num;
q->head = a->next;
deleteAtom(a);
} else {
v = 0;
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment