LinkQueue(链队)

  今天学习了队列,因为前面写了好几个链表实现的数据结构基本上都懂了,然后大致了解了一下队列的特点,便决定用自己的理解来实现一个,然后实现了。

  (2018-02-14 代码更新)

  Head file:

#ifndef __LINKQUEUE_H_
#define __LINKQUEUE_H_

#define bool int
#define true 1
#define false 0

typedef int KeyType;

typedef struct node
{
    struct node * next;
    KeyType key;
}Node;

typedef struct queue
{
    Node * front;
    Node * rear;
    int nums;
}Queue;

Queue * CreateLinkQueue();
bool QueueIsEmpty();
int QueueItemCount();
bool QueueAdd();
bool QueueRemove();
Node* GetQueueFrontNode();
Node* GetQueueRearNode();
KeyType GetQueueFront();
KeyType GetQueueRear();
void TraverseQueue();
void Clear();
void Destroy();

#endif

  LinkQueue.c:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include "lqueue.h"

//建立链队
Queue * CreateLinkQueue(void)
{
    Queue * p;

    p = (Queue*)malloc(sizeof(Queue));
    p->front = p->rear = NULL;
    p->nums = 0;

    return p;
}

//判断队列是否为空
bool QueueIsEmpty(Queue * p)
{
    return p->nums == 0;
}

//返回当前队列个数
int QueueItemCount(Queue * p)
{
    return p->nums;
}

//入队
bool QueueAdd(Queue * p, KeyType DATA)
{
    Node * s;

    s = (Node*)malloc(sizeof(Node));
    s->key = DATA;
    s->next = NULL;
    if(QueueIsEmpty(p))
        p->front = s;
    else
        p->rear->next = s;
    p->rear = s;
    p->nums++;
    return true;
}

//出队
bool QueueRemove(Queue * p)
{
    Node * s;

    if(QueueIsEmpty(p))
        return false;
    s = p->front;
    p->front = p->front->next;
    free(s);
    p->nums--;
    return true;
}

//返回队首节点
Node* GetQueueFrontNode(Queue * p)
{
    if(QueueIsEmpty(p))
        return false;
    return p->front;
}

//返回队尾节点
Node* GetQueueRearNode(Queue * p)
{
    if(QueueIsEmpty(p))
        return false;
    return p->rear;
}

//返回队首
KeyType GetQueueFront(Queue * p)
{
    return GetQueueFrontNode(p)->key;
}

//返回队尾
KeyType GetQueueRear(Queue * p)
{
    return GetQueueRearNode(p)->key;
}

//遍历队列
void TraverseQueue(Queue * p)
{
    Node*s = GetQueueFrontNode(p);
    while(s != NULL)
    {
        printf("%d ", s->key);
        s = s->next;
    }
    printf("\n");
}

//清空队列
void Clear(Queue * p)
{
    while(!QueueIsEmpty(p))
        QueueRemove(p);
}

//销毁队列
void Destroy(Queue * p)
{
    if(p != NULL)
    {
        Clear(p);
        free(p);
        p = NULL;
    }
}

  

转载于:https://www.cnblogs.com/darkchii/p/7383837.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值