栈与队列:循环队列算法+可执行代码
//队列顺序存储结构 //取模运算:就是取余数,它的值永远不会大于除数 (rear+1)%QueueSize (front+1)%QueueSize //队列的顺序存储结构 #define MAXSIZE 100 typedef struct { ElemType *base; //用于存放内存分配基地址 //也可用于数组存放 int front; int rear; }cy initQueue(cycleQueue *q) { q->base = (ElemType *)malloc(MAXSIZE * sizeof(ElemType)); if(!q->base) exit(0); q->front = q->rear = 0; //指向0号单元 } InsertQueue(cycleQueue *q, ElemType e) { if((q->rear+1)%MAXSIZE == Q->front) return;//队列已满 q->base[q->rear] = e; q->rear = (q->rear+1)%MAXSIZE; } DeleteQueue(cycleQueue *q, ElemType *e) { if(q->front == q->rear) return;//队列为空 *e = q->base[q->front]; q->front = (q->front+1)%MAXSIZE; } //循环队列可执行代码 #include<stdio.h> #include<stdlib.h> #define MAXQSIZE 100 //最大长度 #define OVERFLOW 0 #define ERROR -1 #define OK 1 typedef int SElemType; typedef int QElemType; typedef int Status; typedef struct { QElemType *base; //储存空间的基地址 int front; int rear; }sqQueue; Status InitQueue(sqQueue *Q); //初始化 int QueueLength(sqQueue Q); //测量长度 Status EnQueue(sqQueue *Q, QElemType e);//入队列 Status DeQueue(sqQueue *Q, QElemType *e);//出队列 SElemType GetHead(sqQueue Q)//获取头顶元素 Status InitQueue(sqQueue *Q) { Q->base = (QElemType *)malloc(sizeof(QElemType)*MAXQSIZE); if(!Q->base) exit(OVERFLOW); Q->front = Q->rear = 0; return OK; } int QueueLength(sqQueue Q) { return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE; } Status EnQueue(sqQueue *Q, QElemType e) { if((Q->front+1)%MAXQSIZE == Q->front) //判断对是否已满 return ERROR; Q->base[Q->rear] = e; Q->rear = (Q->rear+1)%MAXQSIZE; return OK; } Status DeQueue(sqQueue *Q, QElemType *e) { if(Q->front == Q->rear) { return ERROR; } *e = Q->base[Q->front]; Q->front = (Q->front+1)%MAXQSIZE; return OK; } SElemType GetHead(sqQueue Q) { if(Q.front != Q.rear) return Q.base[Q.front]; } int main(void) { sqQueue q; int e; int len; int ehead; InitQueue(&q); printf("请输入队列元素 以0结束输入:\n"); scanf("%d",&e); while(e != 0) { EnQueue(&q,e); scanf("%d",&e); } len = QueueLength(q); printf("队列的长度是: %d\n",len); ehead = GetHead(q); printf("队列的头顶元素是:%d\n",ehead); printf("队列中的元素是:\n"); while(q.front != q.rear) { DeQueue(&q,&e); printf("%d ",e); } return 0; }