队列

#include <iostream>
using namespace std;

#define MAXSIZE 6  // 环形队列最大容量(实际可用容量为MAXSIZE-1,避免空满判定冲突)
typedef char ElemType;

// 环形队列的结构体
typedef struct {
    ElemType data[MAXSIZE];
    int front;  // 队头指针(指向队头元素)
    int rear;   // 队尾指针(指向队尾元素的下一个位置)
} SqQueue;
// 初始化队列
void InitQueue(SqQueue &q) {
    q.front = q.rear = 0;  // 队头、队尾指针初始化为0
}
// 判断队列是否为空
bool IsEmpty(SqQueue q) {
    return q.front == q.rear;  // 队头队尾指针相等则为空
}
// 入队(元素e插入队尾)
bool EnQueue(SqQueue &q, ElemType e) {
    if ((q.rear + 1) % MAXSIZE == q.front) {  // 队列满
        cout << "队列已满,无法入队!" << endl;
        return false;
    }
    q.data[q.rear] = e;          // 将元素e存入队尾指针指向的位置
    q.rear = (q.rear + 1) % MAXSIZE;  // 队尾指针后移(环形)
    return true;
}
// 出队(队头元素出队,存入e)
bool DeQueue(SqQueue &q, ElemType &e) {
    if (q.front == q.rear) {  // 队列空
        cout << "队列为空,无法出队!" << endl;
        return false;
    }
    e = q.data[q.front];          // 取出队头元素
    q.front = (q.front + 1) % MAXSIZE;  // 队头指针后移(环形)
    return true;
}
// 输出队列序列
void PrintQueue(SqQueue q) {
    if (IsEmpty(q)) {
        cout << "队列为空!" << endl;
        return;
    }
    int i = q.front;
    cout << "队列序列:";
    while (i != q.rear) {  // 从队头遍历到队尾前一个位置
        cout << q.data[i] << " ";
        i = (i + 1) % MAXSIZE;
    }
    cout << endl;
}
// 释放队列(顺序队列无需额外操作)
void DestroyQueue(SqQueue &q) {
    q.front = q.rear = 0;  // 重置队列
    cout << "队列已释放!" << endl;
}
// exp3-3.cpp
int main() {
    SqQueue q;
    ElemType e;

    // (1)初始化队列
    InitQueue(q);
    cout << "(1)队列初始化完成" << endl;

    // (2)判断队列是否为空
    if (IsEmpty(q)) {
        cout << "(2)当前队列是空队列" << endl;
    } else {
        cout << "(2)当前队列不是空队列" << endl;
    }

    // (3)依次入队元素a、b、c
    EnQueue(q, 'a');
    EnQueue(q, 'b');
    EnQueue(q, 'c');
    cout << "(3)元素a、b、c入队完成" << endl;
    PrintQueue(q);

    // (4)出队一个元素,输出该元素
    if (DeQueue(q, e)) {
        cout << "(4)出队的元素是:" << e << endl;
    }
    PrintQueue(q);

    // (5)依次入队元素d、e、f
    EnQueue(q, 'd');
    EnQueue(q, 'e');
    EnQueue(q, 'f');
    cout << "(5)元素d、e、f入队完成" << endl;
    PrintQueue(q);

    // (6)输出出队序列(即当前队列序列)
    cout << "(6)";
    PrintQueue(q);

    // (7)释放队列
    DestroyQueue(q);

    return 0;
}

 

posted @ 2025-10-22 14:00  ouyeye  阅读(5)  评论(0)    收藏  举报