下面的程序中假设:
队首指针指示在当前队首元素的位置,队尾指针在队尾元素+1的位置指示。
- #include <stdio.h>
- #include <malloc.h>
- #define MAXSIZE 5
- typedef char ElemType;
- typedef struct
- {
- ElemType *base;
- int front;
- int rear;
- }SqQueue;
- void Clear(SqQueue *s)
- {
- free(s);
- }
- void InitQueue(SqQueue *s)
- {
- s->base = (ElemType *)malloc(MAXSIZE * sizeof(ElemType));
- if (!s->base)
- {
- printf("error\n");
- return;
- }
- s->front = 0;
- //首、尾指针初始化
- s->rear = s->front;
- }
- int EmptyQueue(SqQueue *s)
- {
- return(s->front == s->rear);
- }
- int QueueLength(SqQueue *s)
- {
- return (s->rear - s->front + MAXSIZE) % MAXSIZE;
- }
- int EnQueue(SqQueue *s,ElemType e)
- {
- if ((s->rear +1) % MAXSIZE == s->front)
- {
- return 0;
- }
- s->base[s->rear] = e;
- s->rear = (s->rear + 1) % MAXSIZE;
- return 1;
- }
- int DeQueue(SqQueue *s,ElemType *e)
- {
- if (s->front == s->rear)
- {
- return 0;
- }
- *e = s->base[s->front];
- s->front = (s->front + 1) % MAXSIZE;
- return 1;
- }
- void main()
- {
- ElemType e;
- SqQueue *s;
- s = (SqQueue *)malloc(sizeof(SqQueue));
- InitQueue(s);
- if (EnQueue(s,'a') == 0)
- {
- printf("队满,不能进队!");
- }
- if (EnQueue(s,'b') == 0)
- {
- printf("队满,不能进队!");
- }
- if (EnQueue(s,'c') == 0)
- {
- printf("队满,不能进队!");
- }
- printf("队列为:%s\n",(EmptyQueue(s)?"空":"非空"));
- if (DeQueue(s,&e) == 0)
- {
- printf("队空,不能出队!\n");
- }
- else
- {
- printf("出队一个元素:% c\n", e);
- }
- printf("队列的元素个数为:%d\n",QueueLength(s));
- if (EnQueue(s,'d') == 0)
- {
- printf("队满,不能进队!\n");
- }
- if (EnQueue(s,'e') == 0)
- {
- printf("队满,不能进队!\n");
- }
- if (EnQueue(s,'f') == 0)
- {
- printf("队满,不能进队!\n");
- }
- printf("队列的元素个数为:%d\n",QueueLength(s));
- while(!EmptyQueue(s))
- {
- DeQueue(s,&e);
- printf("%c",e);
- }
- printf("\n");
- printf("释放队列...\n");
- Clear(s);
- while(!EmptyQueue(s))
- {
- DeQueue(s,&e);
- printf("%c",e);
- }
- printf("释放队列成功\n");
- }
转载于:https://blog.51cto.com/591819849/1100788