• 双端队列


    思路:与队列相同,就是判断是否合法要花费时间,复杂度为O(1);

    在双端队列的表头插入或者在双端队列的表尾进行删除时要注意可能越界,用循环队列的思想取余就好了。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    using namespace std;
    const int maxnszie = 1200;
    struct Node{
        int top,rear,size,capcity;
        int *arry;
    };
    typedef struct Node* DeQue;
    
    int IsEmpty(DeQue q)
    {
        return q->size==0;
    }
    
    int IsFull(DeQue q)
    {
        return q->size==q->capcity;
    }
    
    void MakeEmpty(DeQue q)
    {
        q->rear=0;
        q->size=0;
        q->top=1;
    }
    
    DeQue CreateDeQue(int size)
    {
        DeQue q=new Node;
        if(size>maxnszie) printf("too small
    ");
        q->capcity=size;
        q->arry=(int*)malloc(sizeof(struct Node));
        if(q->arry==NULL) printf("Out of Space!!!
    ");
        MakeEmpty(q);
    }
    
    void Inject(int x,DeQue q)
    {
        if(q->size+1>q->capcity)
        {
            printf("Queue Full
    ");
            return ;
        }
        q->size++;
        q->rear++;
        q->rear%=q->capcity;
        q->arry[q->rear]=x;
    }
    
    int Pop(DeQue q)
    {
        if(!IsEmpty(q))
        {
            int x=q->arry[q->top];
            q->top++;
            q->top%=q->capcity;
            q->size--;
            return x;
        }
    }
    
    void Push(int x,DeQue q)
    {
        if(!IsFull(q))
        {
            q->top--;
            q->size++;
            q->top=(q->top+q->capcity)%q->capcity;
            q->arry[q->top]=x;
        }
    }
    
    int Eject(DeQue q)
    {
        if(!IsEmpty(q))
        {
            int x=q->arry[q->rear];
            q->rear--;
            q->size--;
            q->rear=(q->rear+q->capcity)%q->capcity;
            return x;
        }
    }
    
    int main(void)
    {
        int i,n,x;
        cin>>n;
        DeQue q=CreateDeQue(n);
        for(i=0;i<n;i++)
        {
            cin>>x;
            Inject(x,q);
        }
        
        printf("%d
    ",Pop(q));
        printf("%d
    ",Eject(q));
        while(!IsEmpty(q))
        {
            printf("%d ",Pop(q));
        }
        return 0;
    }
    View Code
  • 相关阅读:
    欧拉回路一个定理的证明
    NOIP2018 初赛数学第二题解析
    linux 减少Terminal路径的方法
    网络挖坑
    linux 记录
    河南游记 Day0

    NOI2018 Day 1 你的名字
    大佬的几行fastIO
    Codeforces 781B. Innokenty and a Football League
  • 原文地址:https://www.cnblogs.com/2018zxy/p/10040305.html
Copyright © 2020-2023  润新知