数据结构之栈(四)

Queue.c

1.头文件的声明

#include "Queue.h"

2.初始化和销毁函数的定义

void QueueInit(Que* pq)
{
    assert(pq);

    pq->head = pq->tail = NULL;
    pq->size = 0;
}

void QueueDestroy(Que* pq)
{
    assert(pq);

    QNode* cur = pq->head;
    while (cur)
    {
        QNode* next = cur->next;
        free(cur);
        cur = next;
    }

    pq->head = pq->tail = NULL;
    pq->size = 0;
}

3.入队列和出队列函数的定义

void QueuePush(Que* pq, QDataType x)
{
    assert(pq);
    QNode* newnode = (QNode*)malloc(sizeof(QNode));
    if (newnode == NULL)
    {
        perror("malloc fail");
        exit(-1);
    }

    newnode->data = x;
    newnode->next = NULL;

    if (pq->tail == NULL)
    {
        pq->head = pq->tail = newnode;
    }
    else
    {
        pq->tail->next = newnode;
        pq->tail = newnode;
    }

    pq->size++;
}

void QueuePop(Que* pq)
{
    assert(pq);//判断队列指针指向是否为空
    assert(!QueueEmpty(pq));//判断队列里面的数据是否为空

    if (pq->head->next == NULL)
    {
        free(pq->head);
        pq->head = pq->tail = NULL;
    }
    else
    {
        QNode* next = pq->head->next;
        free(pq->head);
        pq->head = next;
    }

    pq->size--;
}

4.查找队头、查找队尾函数的定义

//查找队头元素
QDataType QueueFront(Que* pq)
{
    assert(pq);
    assert(!QueueEmpty(pq));

    return pq->head->data;
}

//查找队尾元素
QDataType QueueBack(Que* pq)
{
    assert(pq);
    assert(!QueueEmpty(pq));

    return pq->tail->data;
}

5.判空以及长度计算函数的定义

//判断是否为空
bool QueueEmpty(Que* pq)
{
    assert(pq);

    return pq->head == NULL;
}

//长度计算
int QueueSize(Que* pq)
{
    assert(pq);

    return pq->size;
}

(3)Test.c

1.头文件的声明

#include "Queue.h"

2.测试函数的定义

void QueueTest() {
    Que pq;
    QueueInit(&pq);
    QueuePush(&pq, 1);
    QueuePush(&pq, 2);
    QueuePush(&pq, 3);
    QueuePush(&pq, 4);
    QueuePush(&pq, 5);
    while (!QueueEmpty(&pq)) {
        printf("%d ", QueueFront(&pq));
        QueuePop(&pq);
    }
    QueueDestroy(&pq);
}

 

 

文章链接: https://www.mfisp.com/26238.html

文章标题:数据结构之栈(四)

文章版权:梦飞科技所发布的内容,部分为原创文章,转载请注明来源,网络转载文章如有侵权请联系我们!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
建站教程

数据结构之栈(三)

2023-12-22 10:05:17

建站教程投稿分享

c语言之fcfs

2024-1-29 13:08:26

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
客户经理
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索

梦飞科技 - 最新云主机促销服务器租用优惠