Queue in C
This commit is contained in:
parent
363ac4902c
commit
d3575335fa
1 changed files with 67 additions and 0 deletions
67
queue.c
Normal file
67
queue.c
Normal file
|
@ -0,0 +1,67 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
|
||||
typedef struct {
|
||||
int* elements;
|
||||
int head;
|
||||
int tail;
|
||||
int size;
|
||||
} queue;
|
||||
|
||||
queue* qcreate();
|
||||
void qput(queue *q, int element);
|
||||
int qget(queue *q);
|
||||
int qempty(queue *q);
|
||||
int qfull(queue *q);
|
||||
void qclear(queue* q);
|
||||
|
||||
queue* qcreate(int size) {
|
||||
queue* q = malloc(sizeof(queue));
|
||||
q->elements = malloc(sizeof(int) * size);
|
||||
q->size = size;
|
||||
qclear(q);
|
||||
return q;
|
||||
}
|
||||
|
||||
void qput(queue* q, int element) {
|
||||
assert(q->tail != -1);
|
||||
q->elements[q->tail] = element;
|
||||
q->tail = (q->tail + 1) % q->size;
|
||||
if(q->head == q->tail) q->tail = -1;
|
||||
}
|
||||
|
||||
int qget(queue* q) {
|
||||
assert(q->tail != q->head);
|
||||
if(q->tail == -1) q->tail = q->head;
|
||||
int element = q->elements[q->head];
|
||||
q->head = (q->head + 1) % q->size;
|
||||
return element;
|
||||
}
|
||||
|
||||
int qempty(queue* q) {
|
||||
return (q->head == q->tail);
|
||||
}
|
||||
|
||||
int qfull(queue* q) {
|
||||
return (q->tail == -1);
|
||||
}
|
||||
|
||||
void qclear(queue *q) {
|
||||
q->head = 0;
|
||||
q->tail = 0;
|
||||
}
|
||||
|
||||
void qdestroy(queue *q) {
|
||||
free(q->elements);
|
||||
free(q);
|
||||
}
|
||||
|
||||
int main( int argc, char *argv[] ) {
|
||||
queue* q = qcreate(300);
|
||||
int i = 0;
|
||||
while(!qfull(q)) qput(q,i++);
|
||||
|
||||
while(!qempty(q)) printf("%d\n",qget(q));
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue