Created
March 30, 2009 05:56
-
-
Save kana/87653 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
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; | |
} | |
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 = (atom_t *)malloc(sizeof(atom_t)); | |
a->num = 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; | |
free(a); | |
} else { | |
v = 0; | |
} | |
return v; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment