队列的入队和出队完整代码
时间: 2023-12-24 13:24:20 浏览: 94
队列是一种先进先出(FIFO)的数据结构,它支持在队尾插入元素(入队),在队头删除元素(出队)。以下是队列的入队和出队完整代码:
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 队列最大容量
class Queue {
private:
int data[MAXSIZE]; // 存储队列元素
int front; // 队头指针
int rear; // 队尾指针
public:
Queue() { // 构造函数,初始化队头和队尾指针
front = rear = 0;
}
bool isEmpty() { // 判断队列是否为空
return front == rear;
}
bool isFull() { // 判断队列是否已满
return (rear + 1) % MAXSIZE == front;
}
bool enqueue(int x) { // 入队操作
if (isFull()) {
cout << "Queue is full!" << endl;
return false;
}
data[rear] = x;
rear = (rear + 1) % MAXSIZE;
return true;
}
bool dequeue(int& x) { // 出队操作
if (isEmpty()) {
cout << "Queue is empty!" << endl;
return false;
}
x = data[front];
front = (front + 1) % MAXSIZE;
return true;
}
};
int main() {
Queue q;
int x;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
while (!q.isEmpty()) {
q.dequeue(x);
cout << x << " ";
}
cout << endl;
return 0;
}
```
阅读全文