??1.队列的特点:先进先出(First In First Out)
??2.本篇中讲解循环队列会牺牲一个存储单元(这么做的目的是为了方便判断队满和队空)
#define MaxSize 50
typedef struct {
int data[MaxSize];
int front, rear; //队头指针和队尾指针
}SqQueue;
void InitQueue(SqQueue &Q)
{
Q.front = Q.rear = 0; //初始化对头,队尾指针
}
bool isEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
return false;
}
??入队后,队尾指针的变换 (Q.rear + 1) % MaxSize
bool EnQueue(SqQueue& Q, int e)
{
//判断队满的条件
if ((Q.rear + 1) % MaxSize == Q.front)
return false;
Q.data[Q.rear] = e;
//循环队列
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
??出队以后的对头指针变换 (Q.front + 1) % MaxSize
bool DeQueue(SqQueue& Q,int &e)
{
if (Q.front == Q.rear)
return false; //队空
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
bool GetHead(SqQueue Q, int& e)
{
if (Q.front == Q.rear)
return false; //队空
e = Q.data[Q.front];
return true;
}
int GetLength(SqQueue Q)
{
int len = (Q.rear - Q.front + MaxSize) % MaxSize;
return len;
}
void PrintQueue(SqQueue Q)
{
for (int i = Q.front; i < Q.rear; ++i)
{
cout << Q.data[i]<<" ";
}
}
#include<iostream>
using namespace std;
#define MaxSize 50
typedef struct {
int data[MaxSize];
int front, rear; //队头指针和队尾指针
}SqQueue;
//初始化
void InitQueue(SqQueue &Q)
{
Q.front = Q.rear = 0; //初始化对头,队尾指针
}
//判断空
bool isEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
return false;
}
//入队
bool EnQueue(SqQueue& Q, int e)
{
//判断队满的条件
if ((Q.rear + 1) % MaxSize == Q.front)
return false;
Q.data[Q.rear] = e;
//循环队列
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
//出队
bool DeQueue(SqQueue& Q,int &e)
{
if (Q.front == Q.rear)
return false; //队空
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
//获取队头元素
bool GetHead(SqQueue Q, int& e)
{
if (Q.front == Q.rear)
return false; //队空
e = Q.data[Q.front];
return true;
}
int GetLength(SqQueue Q)
{
int len = (Q.rear - Q.front + MaxSize) % MaxSize;
return len;
}
//打印全部元素
void PrintQueue(SqQueue Q)
{
for (int i = Q.front; i < Q.rear; ++i)
{
cout << Q.data[i]<<" ";
}
}
int main()
{
SqQueue Q;
//初始化
InitQueue(Q);
//判断空
isEmpty(Q);
//入队
int e = 0;
cout << "输入入队的元素:";
cin >> e;
while (e != 9999)
{
EnQueue(Q, e);
cout << "输入入队的元素:";
cin >> e;
}
//出队
DeQueue(Q,e);
cout << "出队元素为:" << e << endl;
//获取队头元素
GetHead(Q, e);
cout << "队头元素为:" << e << endl;
//队列长度
int len = GetLength(Q);
cout << "元素个数为:" << len << endl;
//打印全部元素
PrintQueue(Q);
return 0;
}
有帮助的话,点一个关注哟!