赞
踩
目录
循环队列可以解决假溢出的问题,但对于队满和队空需要有额外的判断,有以下两种方式:
1. 增加变量size用来记录队列中的元素个数,根据size的大小即可判断队列是满是空;
2. 牺牲一个空间,即Front所在的位置不存储元素,队满条件即为:(Rear+1%Maxsize == Front,队空条件即为:Rear == Front;
注:本次基于第二种方法实现对循环队列的基础操作
- typedef int Position;
- typedef int ElementType;
- typedef struct QNode *PtrToNode;
- struct QNode{
- ElementType *data;
- Position front;
- Position rear;
- int Maxsize;
- };
- typedef PtrToNode Queue;
- Queue CreateQueue(int Maxsize){
- Queue Q = (Queue)malloc(sizeof(struct QNode));
- Q->data = (ElementType*)malloc(sizeof(ElementType) * Maxsize);
- Q->front = 0;
- Q->rear = 0;
- Q->Maxsize = Maxsize;
- return Q;
- }
- // 通过浪费一个空间(即Q->front所在的位置)实现队列的空满判断;
- bool IsFull(Queue Q){
- return ((Q->rear + 1) % Q->Maxsize == Q->front);
- }
-
- bool IsEmpty(Queue Q){
- return (Q->front == Q->rear);
- }
- bool Add(Queue Q, ElementType data){
- if(!IsFull(Q)){
- Q->rear = (Q->rear + 1) % Q->Maxsize;
- Q->data[Q->rear] = data;
- return true;
- }
- else{
- printf("队列已满!!!");
- return false;
- }
- }
- ElementType Delete(Queue Q){
- if(!IsEmpty(Q)){
- Q->front = (Q->front + 1) % Q->Maxsize;
- return Q->data[Q->front];
- }
- else{
- printf("队列已空!!!");
- return 0;
- }
- }
完整代码如下:
- #include<stdio.h>
- #include<stdlib.h>
- #include<stdbool.h>
-
- typedef int Position;
- typedef int ElementType;
- typedef struct QNode *PtrToNode;
- struct QNode{
- ElementType *data;
- Position front;
- Position rear;
- int Maxsize;
- };
- typedef PtrToNode Queue;
-
- Queue CreateQueue(int Maxsize){
- Queue Q = (Queue)malloc(sizeof(struct QNode));
- Q->data = (ElementType*)malloc(sizeof(ElementType) * Maxsize);
- Q->front = 0;
- Q->rear = 0;
- Q->Maxsize = Maxsize;
- return Q;
- }
-
- // 通过浪费一个空间(即Q->front所在的位置)实现队列的空满判断;
- bool IsFull(Queue Q){
- return ((Q->rear + 1) % Q->Maxsize == Q->front);
- }
-
- bool IsEmpty(Queue Q){
- return (Q->front == Q->rear);
- }
-
- bool Add(Queue Q, ElementType data){
- if(!IsFull(Q)){
- Q->rear = (Q->rear + 1) % Q->Maxsize;
- Q->data[Q->rear] = data;
- return true;
- }
- else{
- printf("队列已满!!!");
- return false;
- }
- }
-
- ElementType Delete(Queue Q){
- if(!IsEmpty(Q)){
- Q->front = (Q->front + 1) % Q->Maxsize;
- return Q->data[Q->front];
- }
- else{
- printf("队列已空!!!");
- return 0;
- }
- }
-
- void Print(Queue Q){
- while(!IsEmpty(Q)){
- printf("%d\t", Delete(Q));
- }
- }
-
- int main(){
- int Maxsize;
- scanf("%d", &Maxsize);
- Queue Q = CreateQueue(Maxsize);
- int data;
- scanf("%d", &data);
- while(data != -1){//以-1为作为循环终止条件
- Add(Q, data);
- scanf("%d", &data);
- }
- Print(Q);
- return 0;
- }
如有错误,欢迎大家批评指正!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。