跳转至

Queue

1、队列的数组实现

以下是使用数组实现队列的 C++ 代码示例:

C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

using namespace std;

const int MAX_SIZE = 100; // 定义队列的最大容量

class MyQueue {
private:
    int arr[MAX_SIZE]; // 数组存储队列元素
    int front; // 队首下标
    int rear; // 队尾下标
public:
    MyQueue() {
        front = rear = 0; // 初始化队首和队尾下标为0
    }
    bool empty() {
        return front == rear; // 判断队列是否为空
    }
    bool full() {
        return rear == MAX_SIZE; // 判断队列是否已满
    }
    void enqueue(int x) {
        if (full()) {
            cout << "Queue is full" << endl;
            return;
        }
        arr[rear++] = x; // 入队操作
    }
    void dequeue() {
        if (empty()) {
            cout << "Queue is empty" << endl;
            return;
        }
        front++; // 出队操作
    }
    int front_val() {
        if (empty()) {
            cout << "Queue is empty" << endl;
            return -1;
        }
        return arr[front]; // 返回队首元素
    }
};

int main() {
    MyQueue q;
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);
    cout << q.front_val() << endl; // 输出 1
    q.dequeue();
    cout << q.front_val() << endl; // 输出 2
    q.enqueue(4);
    cout << q.front_val() << endl; // 输出 2
    q.dequeue();
    q.dequeue();
    cout << q.front_val() << endl; // 输出 4
    cout << q.empty() << endl; // 输出 0
    q.dequeue();
    cout << q.empty() << endl; // 输出 1
    return 0;
}

​ 在这个示例中,我们首先定义了一个 MyQueue 类,包含一个数组 arr 用于存储队列元素,以及队首和队尾的下标 front 和 rear。在构造函数中,我们将 front 和 rear 的初始值都设置为 0。接着,我们实现了队列的基本操作,包括判断队列是否为空、是否已满,入队操作、出队操作和返回队首元素等。在主函数中,我们创建了一个 MyQueue 对象 q,并依次将元素 1、2、3 加入到队列中,然后输出队列的队首元素(即 1),接着执行了一次出队操作,再次输出队首元素(即 2),并将元素 4 加入到队列中。然后我们又输出了队首元素(即 2),接着执行了两次出队操作,最后输出了队列是否为空的结果。

2、队列的循环数组实现