ADT - 队列

本文介绍了一种链式队列的数据结构实现方法,并详细解释了如何通过C语言进行初始化、插入、删除等核心操作。此外,还提供了完整的源代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define ERROR 0
typedef int Status;
typedef int QElemType;
typedef struct QNode {
    QElemType data;
    struct QNode * next;
}QNode, *QueuePtr;
typedef struct {
    QueuePtr front;
    QueuePtr rear;
}LinkQueue;
//初始化队列
Status InitQueue_L(LinkQueue &Q)
{
    Q.front = (QueuePtr) malloc (sizeof(QNode));
    if (Q.front == NULL)
        exit(OVERFLOW);
    Q.front->next = NULL;
    Q.rear = Q.front;
    return OK;
}
//创建一个队列
void CreatQueue(LinkQueue &Q)
{
    int n;
    printf("请输入循环队列的长度:");
    scanf("%d",&n);
    for (int i = 1; i <=n; i++)
    {
        printf("第%d个元素为:",i);
        scanf("%d",&Q.base[Q.rear]);
        Q.rear=(Q.rear+1)%MAXQSIZE;
    }
}
// 插入元素e为Q的新的队尾元素
Status EnQueue(SqQueue &Q,QElemType e)
{
    if((Q.rear+1)%MAXQSIZE==Q.front)
        return ERROR;
    Q.base[Q.rear]=e;
    Q.rear=(Q.rear+1)%MAXQSIZE;
    return Q.base[Q.rear-1];
}

Status InsertQueue(LinkQueue &Q,QElemType e)        //插入元素e为Q的队尾元素
{
    QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
    if(!p)exit(OVERFLOW);
    p->data = e;         //赋值
    p->next = NULL;
    Q.rear->next = p;        //连接
    Q.rear = p;             //新的队尾
    return OK;
}
//删除队列
Status DeQueue(LinkQueue &Q )            //在队列不为空的情况下,删除队头元素
{
    QElemType e;
    if(Q.front==Q.rear)
     return ERROR;
    e=Q.base[Q.front];
    Q.front=(Q.front+1)%MAXQSIZE;
    return e;
}
//获取队头元素
Status GetFront(LinkQueue Q,QElemType &e)
{
    if (Q.front == Q.rear)
    {
        return ERROR;
    }
    e = Q.front->next->data;
    return e;
}
Status QueueEmpty(LinkQueue Q)
{
    if(Q.front == Q.rear)
    {
        return TRUE;
    }
    else
    {
        return ERROR;
    }
}
//输出队列
Status PrintQueue(LinkQueue Q)
{
    QNode *p;
    p = Q.front->next;
    printf("the queue is:");
    while(p != NULL)
    {
       printf("%d ", p->data);
       p = p->next;
    }
    return OK;
}
//判断队列是否为空
Status EmptyQueue(LinkQueue Q)
{
    if (Q.front->next == NULL)
    return OK;
    return ERROR;
}
//队列的销毁
void DstoryQueue(SqQueue &Q)
{
    while ( Q.front!= Q.rear)
    {
        free(&Q.base[Q.front]);
        Q.front=(Q.front+1)%MAXQSIZE;
    }
}
//清空队列
void  ClearQueue(SqQueue &Q)
{
    int i=Q.front;
    while (i != Q.rear)
    {
        i=0;
        i++;
    }
    Q.front=Q.rear=0;
}
//求队列长度
Status QueueLength(SqQueue Q)
{
    return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
//取队首元素
Status GetHead(SqQueue &Q)
{
    QElemType e;
    if(Q.front==Q.rear)
        return ERROR;
    return e=Q.base[Q.front];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值