循环队列

循环队列

可以解决顺序队列的伪上溢出问题

代码

#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

#define MaxSize 10
typedef struct{
	int data[MaxSize];
	int front,rear;
}SqQueue;

//初始化
void InitQueue(SqQueue &Q){
	Q.rear = Q.front = 0;
}

//判断队空
bool QueueEmpty(SqQueue &Q){
	if (Q.rear == Q.front)
		return true;
	else
		return false;
}

//入队
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.rear == Q.front)
		return false;
	x = Q.data[Q.front];
	Q.front = (Q.front + 1) % MaxSize;
	return true;
}

//读队首元素
bool GetHead(SqQueue &Q,int &x){
	if (Q.rear == Q.front)
		return false;
	x = Q.data[Q.front];
	return true;
}

int main(){
    SqQueue Q;
	InitQueue(Q);

    int n;
    cin >> n;
    for (int i = 0; i < n; i ++)
    {
    	int x;
    	cin >> x;
    	EnQueue(Q,x);
    }

    cout << "Q.front: "<<Q.front << " " << "Q.rear: " << Q.rear << endl;
    
    for (int i = 0; i < n; i ++)
    {
    	int x;
    	DeQueue(Q,x);
    	cout << x << " ";
    }
    
    cout << endl << "Q.front: "<<Q.front << " " << "Q.rear: " << Q.rear << endl;
    return 0;
}
/*
4 
1 0 2 4
/*
上一篇:多项式基本操作


下一篇:最大生成树计数