赞
踩
front:对头下标
rear:队尾下标
入队:cntl->rear++
出队:cntl->front++
队满:(cntl->rear+1)%cntl->size==cntl->front
对空:cntl->rear==cntl->front
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
-
- typedef int Datatype;
-
- //设计队列
- typedef struct Queue
- {
-
- int size;//队长
- Datatype *ptr;//队入口地址
- int front;//对头下标
- int rear;//对尾下标
- }Queue,*P_Queue;
- P_Queue IntiQueue(int Size)
- {
- P_Queue cntl=calloc(1,sizeof(Queue));
-
- if(cntl==NULL)
- {
- printf("申请空间失败\n");
- exit(0);
- }
- cntl->rear=cntl->front=0;
- cntl->size=Size;
- cntl->ptr=calloc(Size,sizeof(Datatype));
-
- return cntl;
- }
- int enQueue(P_Queue cntl,Datatype *data)
- {
- if((cntl->rear+1)%cntl->size==cntl->front)
- {
- printf("队列已经满\n");
- return -1;
- }
- cntl->rear++;
- memcpy(cntl->ptr+cntl->rear,data,sizeof(Datatype));
- printf("入队data:%d\n",*data);
- }
- int outQueue(P_Queue cntl,Datatype *data)
- {
- if(cntl->rear==cntl->front)
- {
- printf("队列为空\n");
- exit(0);
- }
- cntl->front=(cntl->front+1)%cntl->size;
- memcpy(data,cntl->ptr+cntl->front,sizeof(Datatype));
- printf("出队data:%d\n" , *data);
- }
- int main(int argc, char const *argv[])
- {
- P_Queue cntl=IntiQueue(20);
- int data=1;
- for (int i = 0; i <5; i++)
- {
- //添加数据
- enQueue(cntl,&data);
- data=data+2;
- }
- for (int i = 0; i < 8; i++)
- {
- outQueue( cntl , &data);
- }
-
-
- return 0;
- }
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。