数据结构:链队列

#include <iostream>

using namespace std;

typedef int QElemType; // 定义队列元素类型为整型

#define ERROR 0
#define OK 1

// 定义队列结点结构体
typedef struct QNode {
    QElemType data;         // 数据域
    struct QNode *next;     // 指针域
} QNode, *QueuePtr;

// 定义链式队列结构体
typedef struct {
    QueuePtr front;         // 队头指针
    QueuePtr rear;          // 队尾指针
} LinkQueue;

// 初始化链队列
int InitQueue(LinkQueue &Q) {
    Q.front = Q.rear = new QNode; // 创建头结点
    if (!Q.front)
        return ERROR;
    Q.front->next = NULL;
    return OK;
}

// 判断链队列是否为空
int QueueEmpty(LinkQueue Q) {
    return (Q.front == Q.rear);
}

// 获取链队列的队头元素
int GetHead(LinkQueue Q, QElemType &e) {
    if (Q.front == Q.rear)
        return ERROR;
    e = Q.front->next->data;
    return OK;
}

// 链队列入队
int EnQueue(LinkQueue &Q, QElemType e) {
    QueuePtr p;
    p = new QNode;
    if (!p)
        return ERROR;
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    return OK;
}

// 链队列出队
int DeQueue(LinkQueue &Q, QElemType &e) {
    if (Q.front == Q.rear)
        return ERROR;
    QueuePtr p;
    p = Q.front->next;
    e = p->data;
    Q.front->next = p->next;
    if (Q.rear == p)
        Q.rear = Q.front;
    delete p;
    return OK;
}

// 销毁链队列
int DestroyQueue(LinkQueue &Q) {
    QueuePtr p;
    while (Q.front) {
        p = Q.front->next;  // 保存下一个节点的指针
        delete Q.front;
        Q.front = p;        // 更新队头指针
    }
    Q.rear = NULL;          // 队尾指针置空
    return OK;
}

int main() {
    LinkQueue q;
    QElemType e;

    InitQueue(q);

    if (QueueEmpty(q))
        cout << "链队列为空" << endl;
    else
        cout << "链队列不为空" << endl;
        
	cout << "请输入链队列内容:(输入-999结束输入)" << endl;
    cin >> e;
    while (e != -999) {
        EnQueue(q, e);
        cin >> e;
    }

    // DestroyQueue(q);

    GetHead(q, e);
    cout << "链队列的队头元素为: " << e << endl;

	cout << "链队列依次出队:" << endl;
    while (!QueueEmpty(q)) {
        DeQueue(q, e);
        cout << e << " ";
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Terunsu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值