队列的链表实现!

#include <stdio.h>
#include<malloc.h>
typedef char ElemType;

typedef struct qnode
{
    int data;
    struct qnode *next;
}QNode;

typedef struct
{
    QNode *front;
    QNode *rear;
}LiQueue;

//初始化队列
void InitQueue(LiQueue *&q)
{
    q=(LiQueue*)malloc(sizeof(LiQueue));
    q->front=q->rear=NULL;
}

//判断是否为空
int QueueEmpty(LiQueue *q)
{
    if(q->rear==NULL)
        return 1;
    else
        return 0;
}

//释放
void ClearQueue(LiQueue *q)
{
    QNode *p=q->front,*r;
    if(p!=NULL)
    {
        r=p->next;
        while(r!=NULL)
        {
            free(p);
            p=r;r=p->next;
        }
    }
    free(q);
}

//实现队列的入队
void enQueue(LiQueue *q,int e)
{
    //封装结点
    QNode *s;
    s=(QNode*)malloc(sizeof(QNode));
    s->data =e;
    s->next=NULL;
    if(q->rear==NULL)
    {
        q->front =s;
        q->rear =s;
    }
    else
    {
        q->rear->next =s;
        q->rear =s;
    }

}

//出队函数
int deQueue(LiQueue *q,ElemType &e)
{
    QNode *t;
    if(q->rear ==NULL)
        return 0;
    if(q->front ==q->rear )//只有一个结点
    {
        t=q->front ;
        q->front =NULL;
        q->rear =NULL;
    }
    else
    {
        t=q->front;
        q->front=q->front->next;
    }
    e=t->data;
    free(t);
    return 1;
}

//实现队列的测长
int length(LiQueue *q)
{
    int n=0;
    qnode *p;
    p=q->front ;
    while(p!=NULL)
    {
        p=p->next;
        n++;
    }
    return n;
}

void main()
{
    ElemType e;
    LiQueue *q;
    printf("初始化队列q/n");
    InitQueue(q);
    printf("依次进入队列元素a,h,c/n");
    enQueue(q,'a');
    enQueue(q,'h');
    enQueue(q,'c');
    enQueue(q,'d');
    printf("队列为%s/n",(QueueEmpty(q)?"空":"非空"));
    if(deQueue(q,e)==0)
        printf("队空不能出对/n");
    else
        printf("出对一个元素%c/n",e);
    printf("队列的元素个数:%d/n",length(q));
    printf("释放队列/n");
    ClearQueue(q);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值