1. 首页
  2. 编程语言
  3. C
  4. C++队列实现代码:QUEUE.cpp

C++队列实现代码:QUEUE.cpp

上传者: 2023-07-01 02:08:35上传 CPP文件 5.03KB 热度 6次

以下是一个用C++语言实现的队列代码,具体内容如下:

#include<iostream>
using namespace std;

#define MAX 100

class Queue {
private:
    int front, rear;
    int queue[MAX];

public:
    Queue() {
        front = rear = -1;
    }

    void enqueue(int item) {
        if (rear == MAX - 1) {
            cout << "队列已满!无法添加元素。" << endl;
        }
        else {
            if (front == -1) {
                front = 0;
            }
            rear++;
            queue[rear] = item;
            cout << "已向队列中添加元素:" << item << endl;
        }
    }

    void dequeue() {
        if (front == -1 || front > rear) {
            cout << "队列为空!无法删除元素。" << endl;
        }
        else {
            cout << "已从队列中删除元素:" << queue[front] << endl;
            front++;
        }
    }

    void display() {
        if (front == -1) {
            cout << "队列为空!" << endl;
        }
        else {
            cout << "队列元素为:";
            for (int i = front; i <= rear; i++) {
                cout << queue[i] << " ";
            }
            cout << endl;
        }
    }
};

int main() {
    Queue q;

    q.enqueue(10);
    q.enqueue(20);
    q.enqueue(30);

    q.display();

    q.dequeue();

    q.display();

    return 0;
}
iostream>
用户评论