07.队列.顺序队列
2016-07-25 14:47
453 查看
顺序队列
#include "stdio.h" #include "stdlib.h" #include "math.h" #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20 /*存储空间初始分配量*/ typedef int Status; typedef int QElemType; /*QElemType类型根据实际情况而定,这里假设为int*/ //循环队列的顺序存储结构 typedef struct { QElemType data[MAXSIZE]; int front;//头指针 int rear;//尾指针,若队列不空,指向队列尾元素的下一个位置 }SqQueue; /*初始化一个空队列Q*/ Status InitQueue(SqQueue *Q) { Q->front=Q->rear=0; return OK; } /*若队列Q为空队列,则返回TRUE,否则返回FALSE*/ Status QueueEmpty(SqQueue Q) { if(Q.front==Q.rear) return TRUE; else return FALSE; } /*若队列未满,则插入元素e为Q新的队尾元素*/ Status EnQueue(SqQueue *Q,QElemType e) { if((Q->rear+1)%MAXSIZE == Q->front)//队列已满 return ERROR; Q->data[Q->rear]=e; Q->rear=(Q->rear+1)%MAXSIZE;//rear指针向后移一位置,若到最后则转到数组头部 return OK; } /*从队头到队尾依次对队列Q中每个元素输出*/ Status QueueTraverse(SqQueue Q) { int i=Q.front; while(i!=Q.rear) { printf("%d ",Q.data[i]); i=(i+1)%MAXSIZE; } printf("\n"); return OK; } /*返回Q的元素个数,也就是队列的当前长度*/ int QueueLength(SqQueue Q) { return (Q.rear-Q.front+MAXSIZE)%MAXSIZE; } /*若队列不空,则删除Q中队头元素,用e返回其值*/ Status DeQueue(SqQueue *Q,QElemType *e) { if(Q->front==Q->rear)//队列空 return ERROR; *e=Q->data[Q->front]; Q->front=(Q->front+1)%MAXSIZE;//front指针向后移一位置,若到最后则转到数组头部 return OK; } /*若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR*/ Status GetHead(SqQueue Q,QElemType *e) { if(Q.front==Q.rear)//队列空 return ERROR; *e=Q.data[Q.front]; return OK; } /*将Q清为空队列*/ Status ClearQueue(SqQueue *Q) { Q->front=Q->rear=0; return OK; } int main() { Status j; int i=0,l; QElemType d; SqQueue q; InitQueue(&q); printf("初始化队列后,队列空否?%u(1:空 0:否)\n",QueueEmpty(q)); printf("向队列中插入一些数据后: \n"); do { d=i+100; if(d==-1) break; i++; EnQueue(&q,d); }while(i<MAXSIZE-1); QueueTraverse(q); printf("队列长度为: %d\n",QueueLength(q)); printf("现在队列空否?%u(1:空 0:否)\n",QueueEmpty(q)); printf("连续%d次由队头删除元素,队尾插入元素:\n",MAXSIZE); for(l=1;l<=MAXSIZE;l++) { DeQueue(&q,&d); printf("删除的元素是%d,插入的元素:%d \n",d,l+1000); d=l+1000; EnQueue(&q,d); } l=QueueLength(q); printf("现在队列中的元素为: \n"); QueueTraverse(q); j=GetHead(q,&d); if(j) printf("现在队头元素为: %d\n",d); ClearQueue(&q); printf("清空队列后, 队列空否?%u(1:空 0:否)\n",QueueEmpty(q)); return 0; }
相关文章推荐
- C#线程队列用法实例分析
- 算法系列15天速成 第九天 队列
- C语言单链队列的表示与实现实例详解
- mysql 队列 实现并发读
- C#队列Queue用法实例分析
- C#多线程处理多个队列数据的方法
- C语言循环队列的表示与实现实例详解
- C++循环队列实现模型
- C#内置队列类Queue用法实例
- Array栈方法和队列方法的特点说明
- C#通过链表实现队列的方法
- C#队列Queue多线程用法实例
- C#数据结构与算法揭秘五 栈和队列
- C++中队列的建立与操作详细解析
- PHP实现的memcache环形队列类实例
- php基于双向循环队列实现历史记录的前进后退等功能
- 队列在编程中的实际应用(php)
- Go语言的队列和堆栈实现方法
- C++队列用法实例
- PHP队列用法实例