数据结构学习【队列 顺序结构 C++】 顺序队列实现

数据结构学习【队列 顺序结构 C++】


本次实现的是队列的顺序存储结构——顺序队列。

关于如何判断队满、队空

(note:此处rear始终指向队尾的后一个元素)
1.牺牲一个存储空间
入队时少用一个队列单元。此时
队满条件:(Q.rear+1)%MaxSize==Q.front
队空条件:Q.front==Q.rear
2.结构体中增加一个表示元素个数的数据成员 size。此时
队满条件:Q.size==MaxSize
队空条件:Q.size==0
3.结构体中增设一个tag数据成员。
删除操作使得tag=0,加入操作使得tag=1。此时
队满条件:当tag=1,若因为入队操作导致 Q.front== Q.rear,则队满
队空条件:当tag=0,若因为出队操作导致 Q.front== Q.rear,则队空

代码

此处代码采用了第一种方法,通过牺牲一个存储空间来判断队满和队空。
这里的front指针始终指向队头元素(初始化时指向0),rear指针始终指向队尾元素的下一位。

#include <iostream>
using namespace std;
#define MaxSize 10
// ADT
// InitQueue(&Q) //初始化队列
// DestroyQueue(&Q) //销毁队列

// EnQueue(&Q,x) //入队
// DeQueue(&Q,&x) //出队 删除队头元素
// GetHead(Q,&x) //读队头元素 不改变队列

// IsEmpty(Q) //判断队列是否为空
// PrintQueue(Q) //顺序输出队列
typedef struct SqQueue{
    
    
    int data[MaxSize];
    int front,rear;//front--队头(始终指向队头元素,初始时指向0)  rear--队尾(始终指向队尾元素的下一位)
}SqQueue;

// Code
//初始化队列
bool InitQueue(SqQueue &Q){
    
    
    Q.front=Q.rear=0;//初始时,队头队尾均指向0
    return true;
}
//销毁队列
bool DestroyQueue(SqQueue &Q){
    
    
    Q.front=Q.rear=0;
    return true;
}
//入队
bool EnQueue(SqQueue &Q,int x){
    
    
    if((Q.rear+1)%MaxSize==Q.front) //判断栈满
        return false;
    Q.data[Q.rear]=x;
    Q.rear=(Q.rear+1)%MaxSize;
    return true;
}
//出队 删除队头元素
bool DeQueue(SqQueue &Q,int &x){
    
    
    if(Q.front==Q.rear)//队列为空
        return false;
    x=Q.data[Q.front];
    Q.front=(Q.front+1)%MaxSize;
    return true;
} 
//读队头元素 不改变队列
bool GetHead(SqQueue Q,int &x){
    
    
    if(Q.front==Q.rear)//队列为空
        return false;
    x=Q.data[Q.front];
    return true;
}

//判断队列是否为空
bool IsEmpty(SqQueue Q){
    
    
    if(Q.rear==Q.front)
        return true;
    else
        return false;
} 
//顺序输出队列
void PrintQueue(SqQueue Q){
    
    
    printf("队列元素为:");
    int i=Q.front;
    while(i!=Q.rear){
    
    
        printf("%2d ",Q.data[i]);
        i=(i+1)%MaxSize;
    }
    printf("\n");
} 
int main(){
    
    
    SqQueue Q;
    //创建队列并入队元素
    InitQueue(Q);
    EnQueue(Q,1);
    EnQueue(Q,2);
    EnQueue(Q,3);
    EnQueue(Q,4);
    EnQueue(Q,5);
    PrintQueue(Q);
    //出队一个元素
    int x=-1;
    DeQueue(Q,x);
    printf("出队队列元素:%d\n",x);
    PrintQueue(Q);
    //获得栈顶元素
    GetHead(Q,x);
    printf("队列队头元素为:%d\n",x);
    PrintQueue(Q);
    system("pause");

    //这里是为了测试循环队列是否正确
    DeQueue(Q,x);
    DeQueue(Q,x);
    DeQueue(Q,x);
    DeQueue(Q,x);
    EnQueue(Q,1);
    EnQueue(Q,2);
    EnQueue(Q,3);
    EnQueue(Q,4);
    EnQueue(Q,5);
    EnQueue(Q,6);
    EnQueue(Q,7);
    PrintQueue(Q);
    system("pause");
}

结果如图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/toro180/article/details/122414705