zoukankan      html  css  js  c++  java
  • 数据结构之队列

    队列特性:先进先出(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;
        }
    }
    复制代码
  • 相关阅读:
    【Spring】IOC核心源码学习(二):容器初始化过程
    啃啃老菜:Spring IOC核心源码学习(一)
    快速理解Kafka分布式消息队列框架
    浅谈分布式缓存那些事儿
    JVM调优总结
    唉,程序员要是自学能力不行就等死吧!
    游戏开发入门
    JVM源码分析-Java运行
    Java阻塞队列的实现
    Java中堆内存和栈内存详解
  • 原文地址:https://www.cnblogs.com/Ph-one/p/6396265.html
Copyright © 2011-2022 走看看