1. 假设用flag作为区分循环队列空和非空的标志,设定flag=0为队列空,flag=1为队列非空,初始flag=0.请写出循环队列的入队与出队算法。当入队之前遇到队列满,以及出队之前遇到队列空时,需要打印警告。 template <class ElemType> class CyQueue{ public: int front;//queue[front]是头结点,不存数据 int rear; int MaxSize; bool flag; ElemType *queue; CyQueue(int ms){ flag=0;front=0;rear=0; MaxSize=ms; queue=new ElemType[ms+5]; //分配一个足够大的空间 } void EnQueue(CyQueue &Q, ElemType x); ElemType OutQueue(CyQueue& Q); }; template <class ElemType> void CyQueue<ElemType>::EnQueue(CyQueue &Q, ElemType x) { } template <class ElemType> ElemType CyQueue<ElemType>::OutQueue(CyQueue &Q) { }
时间: 2023-06-19 10:05:14 浏览: 176
循环队列的入队算法如下:
```c++
template <class ElemType> void CyQueue<ElemType>::EnQueue(CyQueue &Q, ElemType x) {
if (Q.flag && (Q.rear + 1) % (Q.MaxSize + 1) == Q.front) {
cout << "队列已满,无法插入新元素!" << endl;
return;
}
Q.queue[Q.rear] = x;
Q.rear = (Q.rear + 1) % (Q.MaxSize + 1);
Q.flag = 1;
}
```
循环队列的出队算法如下:
```c++
template <class ElemType> ElemType CyQueue<ElemType>::OutQueue(CyQueue& Q) {
if (!Q.flag) {
cout << "队列为空,无法删除元素!" << endl;
return Q.queue[Q.front];
}
ElemType x = Q.queue[Q.front];
Q.front = (Q.front + 1) % (Q.MaxSize + 1);
if (Q.front == Q.rear) {
Q.flag = 0;
}
return x;
}
```
其中,入队算法中,我们首先判断队列是否已满,如果已满,则打印警告信息并直接返回;如果未满,则将元素 x 插入到队列尾部,并将 rear 指针向后移动一个位置,最后将 flag 标记为非空。
出队算法中,我们首先判断队列是否为空,如果为空,则打印警告信息并返回队头元素;如果不为空,则将队头元素 x 删除,并将 front 指针向后移动一个位置。如果此时队列为空,那么将 flag 标记为 0。最后返回被删除的元素 x。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)