Created
November 22, 2013 19:45
-
-
Save qassa/7605692 to your computer and use it in GitHub Desktop.
Данные queue:
MAXSIZ - (константа) максимальное количество элементов в очереди.
data - массив данных.
top - индекс первого элемента в очереди.
Интерфейс queue:
push - положить значение value в очередь q.
В случае переполнения значение в очередь помещено не будет.
pop - извлечь значение из очереди q.
back - получить последний элемент из очереди q…
This file contains 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
#include <stdio.h> | |
#include <assert.h> | |
#define MAXSIZ 10 | |
typedef struct { | |
int data[MAXSIZ]; | |
int top; | |
} queue_t; | |
void push(queue_t *q, int value) { | |
assert(q != NULL); | |
if(q->top == MAXSIZ) { | |
fprintf(stderr, "queue overflow\n"); | |
return; | |
} | |
q->data[q->top++] = value; | |
} | |
void pop(queue_t *q) { | |
int i = 0; | |
assert(q != NULL); | |
if(q->top == 0) { | |
fprintf(stderr, "queue is empty\n"); | |
return; | |
} | |
for(i = 0; i < q->top && i < MAXSIZ; ++i) | |
q->data[i] = q->data[i+1]; | |
--(q->top); | |
} | |
int back(queue_t *q) { | |
assert(q != NULL); | |
if(q->top == 0) { | |
fprintf(stderr, "queue is empty\n"); | |
return 0; | |
} | |
return q->data[q->top - 1]; | |
} | |
int front(queue_t *q) { | |
assert(q != NULL); | |
if(q->top == 0) { | |
fprintf(stderr, "queue is empty\n"); | |
return 0; | |
} | |
return q->data[0]; | |
} | |
int empty(queue_t *q) { | |
assert(q != NULL); | |
return q->top == 0; | |
} | |
int size(queue_t *q) { | |
assert(q != NULL); | |
return q->top; | |
} | |
void create(queue_t *q) { | |
int i = 0; | |
assert(q != NULL); | |
q->top = 0; | |
for(i = 0; i < MAXSIZ; ++i) | |
q->data[i] = 0; | |
} | |
int main() | |
{ | |
int i = 0; | |
queue_t q; | |
create(&q); | |
for(i = 0; i < 10; ++i) | |
push(&q, i + 1); | |
while(!empty(&q)) { | |
printf("%d -> ", front(&q)); | |
pop(&q); | |
} | |
printf("\b\b\b \n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment