• 队列(转载)


    队列特性:先进先出(FIFO)——先进队列的元素先出队列。来源于我们生活中的队列(先排队的先办完事)。

    队列有下面几个操作:

    • InitQueue()   ——初始化队列
    • EnQueue()        ——进队列
    • DeQueue()        ——出队列
    • IsQueueEmpty()——判断队列是否为空
    • IsQueueFull()    ——判断队列是否已满

    队列可以由数组和链表两种形式实现队列操作(c语言),下面仅以数组为例:

    数组实现:

    队列数据结构

    typedef struct queue
    {
            int queuesize;   //数组的大小
            int head, tail;  //队列的头和尾下标
            int *q;          //数组头指针
    }Queue;

    InitQueue()   ——初始化队列

    void InitQueue(Queue *q)
    {
            q->queuesize = 8;
            q->q = (int *)malloc(sizeof(int) * q->queuesize); //分配内存
            q->tail    = 0;
            q->head = 0;
    }

    这样有个缺陷,空间利用率不高。采用循环队列:

    EnQueue()        ——进队列

    void EnQueue(Queue *q, int key)
    {
            int tail = (q->tail+1) % q->queuesize; //取余保证,当quil=queuesize-1时,再转回0
            if (tail == q->head)                   //此时队列没有空间
            {
                printf("the queue has been filled full!");
            }
            else
            {
                q->q[q->tail] = key;
                q->tail = tail;
            }
    }

    DeQueue()        ——出队列

    int DeQueue(Queue *q)
    {
            int tmp;
            if(q->tail == q->head)     //判断队列不为空
            {
                printf("the queue is NULL
    ");
            }
            else
            {
                tmp = q->q[q->head];
                q->head = (q->head+1) % q->queuesize;
            }
            return tmp;
    }

    IsQueueEmpty()——判断队列是否为空

    int IsQueueEmpty(Queue *q)
    {
            if(q->head == q->tail)
            {
                return 1;
            }
            else
            {
                return 0;
            }
    }

    IsQueueFull()——判断队列是否已满

    int IsQueueFull(Queue *q)
    {
        if((q->tail+1)% q->queuesize == q->head)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
  • 相关阅读:
    Intel 编译器 线程安全检查 真心的很详细 转
    当前软件设计分析
    当代并行机系统
    多人游戏服务器
    ACE源代码目录结构
    (转!)Z buffer和W buffer简介
    数据库-视图(View)详解
    推荐一个vs自带工具分析代码的复杂度
    SCOPE_IDENTITY的用法
    vs2013开发调试cocos2d-x-Lua工程项目
  • 原文地址:https://www.cnblogs.com/yaoyueduzhen/p/4403336.html
Copyright © 2020-2023  润新知