假设以数组Q[m]存放循环队列中的元素, 同时设置一个标志tag,以tag = 0 和 tag = 1来区别在队头指针(front)和队尾指针(rear)相等时,队列状态为“空”还是“满”。试设计与此结构相应的插入和删除算法,编写代码,并带入数据运行验证通过
时间: 2023-05-25 18:02:09 浏览: 59
插入算法:
1. 若队列满,则插入失败,返回错误信息。
2. 将元素插入队尾指针所指位置。
3. 修改队尾指针,若队尾指针已达到数组最后一位,则置为0;否则加1。
4. 若队头指针等于队尾指针,将tag值置为1,否则置为0。
删除算法:
1. 若队列为空,则删除失败,返回错误信息。
2. 取出队头指针所指位置的元素,并将队头指针加1。
3. 若队头指针已达到数组最后一位,则置为0。
4. 若队头指针等于队尾指针,将tag值置为0,否则置为1。
代码实现:
```C++
#define MAX_SIZE 10
class Queue {
private:
int Q[MAX_SIZE];
int front, rear, tag;
public:
Queue() {
front = rear = 0;
tag = 1;
}
bool isEmpty() {
return (front == rear && tag == 0);
}
bool isFull() {
return (front == rear && tag == 1);
}
bool enQueue(int data) {
if (isFull())
return false;
Q[rear] = data;
rear = (rear + 1) % MAX_SIZE;
tag = 0;
return true;
}
bool deQueue(int &data) {
if (isEmpty())
return false;
data = Q[front];
front = (front + 1) % MAX_SIZE;
tag = 1;
return true;
}
};
```
验证数据:
```C++
int main() {
Queue q;
int val;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
q.enQueue(4);
q.enQueue(5);
q.deQueue(val);
q.deQueue(val);
q.deQueue(val);
q.enQueue(6);
q.enQueue(7);
q.enQueue(8);
q.enQueue(9);
q.deQueue(val);
q.deQueue(val);
q.deQueue(val);
q.deQueue(val);
q.enQueue(10);
q.enQueue(11);
if (q.enQueue(12))
cout << "Enqueue successfully!" << endl;
else
cout << "Enqueue failed!" << endl;
if (q.deQueue(val))
cout << "Dequeue successfully!" << endl;
else
cout << "Dequeue failed!" << endl;
return 0;
}
```
输出结果为:
```
Enqueue successfully!
Dequeue successfully!
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)