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

    队列

        1.定义:队列是一种先进先出(FIFO)的线性表。它只允许在表的一端进行插入,而在另一端删除元素。

    在队列中,允许插入的一端叫做队尾,允许删除的一端则称为队头。

        假设对列为q=(a1,a2,a3,...,an),那么a1就是队头元素,an则是队尾元素。队列中的元素是按照a1,a2

    ,...,an的顺序进入的,退出队列也只能按照这个次退出,也就是说,只有在a1,a2,...,an-1都离开队列之后,

    an才能退出队列。那么其数据结构为:

    #define ElemType int
    #define QUEUE_INIT_SIZE 8
    
    typedef struct Queue
    {
        ElemType *base;
        int       capacity;
        int       front;
        int       rear;
    }Queue;

            2.因此在队列中有以下操作:

    void InitQueue(Queue *q);
    void EnQueue(Queue *q, ElemType x);
    void DeQueue(Queue *q);
    ElemType GetTop(Queue *q);
    void ShowQueue(Queue *q);
    bool IsFull(Queue *q);
    bool IsEmpty(Queue *q);

         以上的方法在队列中有以下操作:(1)初始化队列.(2)向队列中插入元素.(3)删除队列中的元素.(4)

    得到队头元素.(5)展示队列中的内容.(6)判断队列是否是满状态.(7)判断队列是否是空状态.

       3.将上面声明的方法进行实现为:

    bool IsFull(Queue *q)
    {
        //return (q->rear-q->front) >= q->capacity;
        //return q->rear >= q->capacity;
        return (q->rear+1)%q->capacity == q->front;
    }
    bool IsEmpty(Queue *q)
    {
        return q->front == q->rear;
    }
    void InitQueue(Queue *q)
    {
        q->base = (ElemType*)malloc(sizeof(ElemType)*QUEUE_INIT_SIZE);
        assert(q->base != NULL);
        q->capacity = QUEUE_INIT_SIZE;
        q->front = q->rear = 0;
    }
    void EnQueue(Queue *q, ElemType x)
    {
        if(!IsFull(q))
        {
            q->base[q->rear] = x;
            q->rear = (q->rear+1) % q->capacity;
        }
    }
    
    void ShowQueue(Queue *q)
    {
        if(!IsEmpty(q))
        {
            for(int i=q->front; i!=q->rear; i=(i+1)%q->capacity)
            {
                cout<<q->base[i]<<" ==> ";
            }
            cout<<endl;
        }
    }
    
    void DeQueue(Queue *q)
    {
        if(!IsEmpty(q))
        {
            q->front++;
            q->front = q->front % q->capacity;
        }
    }
    
    ElemType GetTop(Queue *q)
    {
        assert(!IsEmpty(q));
        return q->base[q->front];
    }
  • 相关阅读:
    单页面 Web 应用(Single Page Application,SPA)的工作原理介绍
    为什么 Web 开发人员需要学习一个 JavaScript 框架?
    SAP Commerce Cloud 项目 Spartacus 入门
    SAP Spartacus 的 CSS 架构
    什么是 Immutable Web Apps
    PHP中把stdClass Object转array的几个方法
    git tag常用操作
    报错No Input file specified
    python爬取抖音个人主页所有视频
    无水印抖音视频批量下载---基于python爬虫(全网最简单方法含详细解析)
  • 原文地址:https://www.cnblogs.com/XNQC1314/p/8672495.html
Copyright © 2011-2022 走看看