循环队列的基本操作(初始化,入队,出队,取队头,遍历输出)

#include
#define MaxSize 5
typedef struct {
	int data[MaxSize];
	int front,rear;
}SqQueue;
void InitQueue(SqQueue &Q){
	Q.front = Q.rear = 0;
}
//进队 
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 Print(SqQueue Q){
	if(Q.front == Q.rear)
		return false;
	int i = Q.front;
	while ((i + MaxSize) % MaxSize != Q.rear)//条件相等说明访问到了最后一个元素 
	{
		printf("%d ",Q.data[i]);
		i++;
	}
	printf("\n");
	return true;
}
int main(){
	SqQueue Q;
	InitQueue(Q);
	EnQueue(Q,1);
	EnQueue(Q,2);
	Print(Q);
	return 0;
} 

你可能感兴趣的:(数据结构)