模拟循环队列

注意点:题中所说的最大空间为n,由于我们的尾指针需要额外的占用一个空间,所以在申请空间的时候要多申请一个。

#include<bits/stdc++.h>

using namespace std;

struct node{
    int max;
    int f,r;
    int* next;
};

typedef node* Q;

Q initQueue(int max){
    Q head=(Q)malloc(sizeof(node));
    if(head!=NULL){
        head->max=max+1;
        head->next=(int*)malloc(sizeof(int)*(max+1));
        head->f=0;
        head->r=0;
        return head;
    }else{
        return NULL;
    }
}
int n,q,x;
string s;
int main(){
    
    cin >> n >> q;
    Q head=initQueue(n);
    while(q--){
        cin >> s;
        if(s=="push"){
            cin >> x;
            if((head->r+1)%head->max==head->f){
                cout << "full" << endl;
            }else{
                head->next[head->r]=x;
                head->r=(head->r+1)%head->max;
            }
        }else if(s=="front"){
            if(head->r==head->f){
                cout << "empty" << endl;
            }else{
                cout << head->next[head->f] << endl;
            }
        }else if(s=="pop"){
            if(head->r==head->f){
                cout << "empty" << endl;
            }else{
                cout << head->next[head->f] << endl;
                head->f=(head->f+1)%head->max;
            }
        }
    }
    return 0;
}