#include <stdio.h> #include <malloc.h> typedef struct sq { int maxsize; int front, rear; int *quence; }Qs; void init_quence(Qs *s, int ms) /*初始化队列*/ { s->maxsize = ms; s->quence = (int *)malloc(ms*sizeof(int)); s->front = s->rear = 0; } void in_quence(Qs *s, int val) /*入队函数*/ { if((s->rear+1)%s->maxsize == s->front) { printf("Quence is full.\n"); return; } s->rear = (s->rear+1)%s->maxsize; s->quence[s->rear] = val; } int out_quence(Qs *s) /*出队函数*/ { if(s->rear != s->front) { s->front = (s->front+1)%s->maxsize; return s->quence[s->front]; } } void print_quence(Qs *s) /*打印队列中元素*/ { int i; i = s->front; if(s->rear == s->front) return; do { printf("%d ", s->quence[(i+1)%s->maxsize]); i = (i+1)%s->maxsize; }while(i != s->rear); } void clear_quence(Qs *s) /*清除队列*/ { free(s->quence); s->quence = 0; s->maxsize = 0; s->front = s->rear = 0; } int count_quence(Qs *s) /*统计队列个数*/ { int i, count = 0; i = s->front; if(s->rear == s->front) return 0; do { count ++; i = (i+1)%s->maxsize; }while(i != s->rear); return count; } int main() { Qs s; int i; int dat[7] = {1, 2, 3, 4, 5, 6, 7}; init_quence(&s, 7); for(i = 0; i < 7; i++) { in_quence(&s, dat[i]); printf("Quence number is: %d. ", count_quence(&s)); print_quence(&s); printf("\n"); } printf("Out quence number is: %d.\n", out_quence(&s)); print_quence(&s); clear_quence(&s); return 0; }
程序运行截图:
队列(一)——队列的数组实现方式,布布扣,bubuko.com
原文地址:http://blog.csdn.net/laoniu_c/article/details/38371775