双端队列
思路:与队列相同,就是判断是否合法要花费时间,复杂度为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\n"); q->capcity=size; q->arry=(int*)malloc(sizeof(struct Node)); if(q->arry==NULL) printf("Out of Space!!!\n"); MakeEmpty(q); } void Inject(int x,DeQue q) { if(q->size+1>q->capcity) { printf("Queue Full\n"); 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\n",Pop(q)); printf("%d\n",Eject(q)); while(!IsEmpty(q)) { printf("%d ",Pop(q)); } return 0; }