队列的创建,增加,删除,判断空满
#include <iostream>
#include <cstdlib>
#define ERROR -1
#define N 100
using namespace std;
/*队列*/
struct Queue{
int *data;
int front,rear;
int MaxSize;
};
/*二叉树*/
struct BinTree{
int data;
struct BinTree *left;
struct BinTree *right;
};
/*队列的创建*/
struct Queue *CreateQueue(int Maxsize)
{
struct Queue *Q = (struct Queue *)malloc(sizeof(struct Queue));
Q->data = (int *)malloc(sizeof(int));
Q->front = Q->rear = 0;
Q->MaxSize = Maxsize;
return Q;
}
/*判断队列是否为满*/
bool Isfull(struct Queue *Q)
{
return ((Q->rear+1) % Q->MaxSize == Q->front);
}
/*队列的插入*/
bool AddQ(struct Queue *Q,int x)
{
if(Isfull(Q))
{
cout << "队列已满" << endl;
return false;
}
else
{
Q->rear = (Q->rear+1) % Q->MaxSize;
Q->data[Q->rear] = x;
return true;
}
}
/*判断队列是否为空*/
bool IsEmpty(struct Queue *Q)
{
return (Q->front == Q->rear);
}
/*删除并返回队列头元素*/
int DeleteQ(struct Queue *Q)
{
if(IsEmpty(Q))
{
cout << "队列为空" << endl;
return ERROR;
}
else
{
Q->front = (Q->front+1) % Q->MaxSize;
return Q->data[Q->front];
}
}
int main()
{
int n,x;
struct Queue *Q = CreateQueue(N);
cout << "请输入数据个数";
cin >> n;
while(n--)
{
cin >> x;
AddQ(Q,x);
}
//cout << Q->front << " " << Q->rear << endl;
for(int i = Q->front;i != Q->rear+1;i = (i+1)%Q->MaxSize)
{
cout << Q->data[i] << " ";
}
return 0;
}
|