题解 | #【模板】循环队列#

【模板】循环队列

https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
//因为有规定空间大小,所以适合使用顺序存储来构建队列

//队列
typedef int  positon ;//要判断队列是否为满
typedef  struct QNode* Queue ;
struct QNode{
    positon front,rear;
    int* data;
    int Maxsize;
    int size;
};
//构造队列,返回队列
Queue creatQueue(int num){
    Queue Q = (Queue)malloc(sizeof(struct QNode));  
    // Q->data = (int*) malloc(sizeof(int));
     //分配错内存空间,应该为动态内存
    Q->data = (int*)malloc((num + 1)* sizeof(int));
    Q->front = 0;//不能为null
    Q->rear = 0;
    Q->Maxsize = num;//动态分配内存
    Q->size = num + 1;//循环队列容量初始值
    return Q;
}

//判断队列是否为空
bool IsEmpty(Queue Q){
    return Q->front == Q->rear;
}
//判断队列是否已满
bool IsFull(Queue Q){
   return (Q->rear + 1) % Q->size == Q->front;//取模为零即为满
}
//插入函数,push
int push(Queue Q ,int x){
    if(IsFull( Q)){
        printf("full\n");
         return -1;
    }
    else {
        Q->rear = (Q->rear + 1) % Q->size;//将队尾指针向后移动保证插入合法
        return Q->data[Q->rear] = x;
    }
}

//删除函数
int pop(Queue Q){
    if(IsEmpty( Q)){
        printf("empty\n");
        return -1;
    }
    else {
        Q->front = (Q->front + 1) % Q->size;//将指针往后移
        return Q->data[Q->front];
    }
}

//输出队首元素
int Front(Queue Q) {
    if (IsEmpty(Q)) {
        printf("empty\n");
         return -1;
    } else {
        return Q->data[(Q->front + 1) % Q->size];
    }
}


int main() {
    int a, b;//a为循环队列可利用的空间,b为操作次数
    scanf("%d",&a);
    scanf("%d",&b);
    char ch[10000] ;
    //构建队列
    Queue Q = creatQueue(a);
    for (int i = 0; i < b; i++) {
        scanf("%s", ch);
        //执行插入操作
        if (strcmp(ch , "push") == 0) {
            int num;
            scanf("%d",&num);
            if ( !IsFull(Q)) {
                push( Q, num);  
            }
            else {
                printf("full\n");
            }
            
        }
        else if (strcmp(ch , "pop") == 0) {
            if ( ! IsEmpty(Q)) {
                int popData = pop(Q);
                printf("%d\n",popData);    
            }
            else {
                printf("empty\n");
               
            }
           
        }
        else if (strcmp(ch , "front") == 0) {
            if (! IsEmpty(Q)) {
                // Front(Q);
                // printf("%d\n" ,Front(Q));//调用了两次相同的函数  
               int frontData =  Front(Q);
                printf("%d\n",frontData);
                
            }
            else {
                printf("empty\n");
                
            }
        }
    }

    
    
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务