队列的实现与基本操作

*

1.链队列

*
存储结构:

typedef struct LQNode
{
    DataType info;
    struct LQNode *next;
}LQNode;

typedef struct
{
    struct LQNode *front;
    struct LQNode *rear;
}LinkQueue;

基本操作的实现:

//创建空队列
LinkQueue *LQueueCreateEmpty()
{
    LinkQueue *plq=(LinkQueue*)malloc(sizeof(LinkQueue));
    LQNode *p=(LQNode*)malloc(sizeof(LQNode));
    p->next=NULL;
    plq->front=plq->rear=p;
    return plq;
}

//判断队列是否空
int LQueueIsEmpty(LinkQueue *plq)
{
    if(plq->front==plq->rear)
    {
        return TRUE;
    }
    else
        return FALSE;
}

//入队
void LQueueEnqueue(LinkQueue *plq,DataType x)
{
    LQNode *p=(LQNode*)malloc(sizeof(LQNode));
    if(p==NULL)
        printf("内存分配失败\n");
    else
    {
        p->info=x;
        p->next=NULL;
        plq->rear->next=p;
        plq->rear=p;
    }
}

//出队
int LQueueDeQueue(LinkQueue *plq,DataType *x)
{
    LQNode *p;
    if(plq->front==plq->rear)
    {
        printf("队列空\n");
        return ERROR;
    }
    else
    {
        p=plq->front->next;
        *x=p->info;
        plq->front->next=p->next;
        free(p);
        return OK;
    }
}

//返回队首元素
DataType LQueueFront(LinkQueue *plq)
{
    if(plq->front==plq->rear)
    {
        printf("队列空\n");
        exit(0);
    }
    return (plq->front->next->info);
}

*

2.循环队列

*

存储结构:

typedef struct
{
    int front,rear;
    DataType data[MAXSIZE];
}SeqQueue;

基本操作的实现:

//创建
SeqQueue *SQueueCreate()
{
    SeqQueue *sq=(SeqQueue*)malloc(sizeof(SeqQueue));
    if(sq==NULL)
        printf("溢出\n");
    else
        sq->front=sq->rear=0;
    return sq;
}

//判空
int SQueueIsEmpty(SeqQueue *sq)
{
    if(sq->front==sq->rear)
        return TRUE;
    else 
        return FALSE;
}

//入队
void SQueueEnQueue(SeqQueue *sq,DataType x)
{
    if((sq->rear+1)%MAXSIZE==sq->front)
        printf("队列满");
    else
    {
        sq->rear=(sq->rear+1)%MAXSIZE;
        sq->data[sq->rear]=x;
    }
}

//出队
int SQueueDeQueue(SeqQueue *sq,DataType *e)
{
    if(sq->front==sq->rear)
    {
        printf("队空\n");
        return ERROR;
    }
    else
    {
        sq->front=(sq->front+1)%MAXSIZE;
        *e=sq->data[sq->front];
        return OK;
    }
}

//取队首元素
DataType SQueueFront(SeqQueue *sq)
{
    if(sq->front==sq->rear)
    {
        printf("队空下溢\n");
        return ERROR;
    }
    else
        return (sq->data[(sq->front+1)%MAXSIZE]);
}

//输出循环队列
void SQueuePrint(SeqQueue *sq)
{
    int i=(sq->front+1)%MAXSIZE;
    while(i!=sq->rear+1)
    {
        printf("\t%d",sq->data[i]);
        i=(i+1)%MAXSIZE;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值