链式队列实现

LinkQueue.h

#include<stdio.h>
#include<malloc.h>
#include<assert.h>

#define ElemType int

//链式队列

typedef struct QueueNode
{
    ElemType data;
    struct QueueNode *next;
}QueueNode;

typedef struct LinkQueue
{
    QueueNode *front;
    QueueNode *tail;

}LinkQueue;

void InitQueue(LinkQueue *Q);
void EnQueue(LinkQueue *Q, ElemType x);
void ShowQueue(LinkQueue *Q);
void DeQueue(LinkQueue *Q);
void GetHead(LinkQueue *Q, ElemType *v);
int Length(LinkQueue *Q);
void ClearQueue(LinkQueue *Q);
void DestroyQueue(LinkQueue *Q);

LinkQueue.c

 #include"LinkQueue.h"

//构造一个空队列Q

void InitQueue(LinkQueue *Q)
{

    //结点s相当于头结点指针
    QueueNode *s = (QueueNode *)malloc(sizeof(QueueNode));
    assert(s != NULL);

    //front和tail都是代表头结点,数据域为空,不存数据
    Q->front = Q->tail = s;
    Q->tail->next = NULL;
}

//入队,将元素x插入队尾

void EnQueue(LinkQueue *Q, ElemType x)
{

    //申请一个新节点
    QueueNode *s = (QueueNode *)malloc(sizeof(QueueNode));
    assert(s != NULL);
    s->data = x;
    s->next = NULL;

    //尾插法插入新节点s

    Q->tail->next = s;
    Q->tail = s;
}

//遍历队列元素

void ShowQueue(LinkQueue *Q)
{

    //从对头开始遍历队列
    QueueNode *p = Q->front->next;
    printf("Front:>");
    while(p != NULL)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("<:Tail.\n");
}

//出队

void DeQueue(LinkQueue *Q)
{

    //判断是否为空队列
    if(Q->front == Q->tail)
        return;

    

    QueueNode *p = Q->front->next;

    Q->front->next = p->next;
    free(p);

    //p指向最后一个节点,置为空队列
    if(p == Q->tail)
        Q->tail = Q->front;
}

//取出对头元素,存到v中

void GetHead(LinkQueue *Q, ElemType *v)
{

    //空队列直接返回
    if(Q->front == Q->tail)
        return;

    //Q-front是头结点,从开始结点取数据
    QueueNode *p = Q->front->next;
    *v = p->data;
}

//求队列的长度,即队列的元素个数

int Length(LinkQueue *Q)
{
    int len = 0;
    QueueNode *p = Q->front->next; //跳过头结点
    while(p != NULL)
    {
        len++;
        p = p->next;
    }
    return len;
}

//清空队列

void ClearQueue(LinkQueue *Q)
{
    if(Q->front == Q->tail)
        return;

    //请空队列保留头结点
    QueueNode *p = Q->front->next;
    while(p != NULL)
    {
        Q->front->next = p->next;
        free(p);
        p = Q->front->next;
    }
    Q->tail = Q->front;
}

void DestroyQueue(LinkQueue *Q)
{
    ClearQueue(Q);
    free(Q->front);
    Q->front = Q->tail = NULL;
}

main.c测试接口

 #include"LinkQueue.h"

void main()
{
    LinkQueue Q;
    InitQueue(&Q);

    for(int i=1; i<=10; ++i)
    {
        EnQueue(&Q,i);
    }
    ShowQueue(&Q);
    DeQueue(&Q);
    DeQueue(&Q);
    ShowQueue(&Q);
    printf("Len = %d\n",Length(&Q));
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值