题解 | #【模板】队列#

【模板】队列

https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549

#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
#include <string.h>
typedef struct Node*  PtrToNode ;
//链表节点
struct Node {
    int Data;
    PtrToNode Next;//指针
};
//队列
typedef PtrToNode Position ;
typedef struct QNode* Queue ;
struct QNode {
    Position front, rear;//头和尾指针
    int MaxSize;//最大容量
};
Queue CreatQueue() {
    //分配内存空间
    Queue Q = (Queue) malloc(sizeof(struct QNode));
    Q->front = NULL;
    Q->rear = NULL;
    Q->MaxSize =  100000;
    return Q;
}
//判断队列是否为空
bool IsEmpty(Queue Q) {
    return Q->front == NULL;
}
//插入操作,插入队尾
void push(Queue Q, int x) {
    Position NewCode = (Position) malloc(sizeof(struct Node));
    NewCode->Data = x;
    //插入尾部
    NewCode->Next = NULL;
    if (IsEmpty(Q)) {
        Q->front = Q->rear = NewCode;
    } else {
        Q->rear->Next = NewCode;
        Q->rear = NewCode;
    }
}
//删除操作,删除头部元素
int pop(Queue Q) {

    if (IsEmpty(Q)) {
        printf("error\n");
        return -1;
    }
    int x = Q->front->Data;
    Position temp = Q->front;
    Q->front = Q->front->Next;
    //当只有一个元素时
    if (Q->front == NULL) {
        Q->rear = NULL;
    }
    free (temp);//释放空间

    return x;
}
//输出队首,队首不出队
int Front(Queue Q) {
    if (IsEmpty(Q)) {
        printf("error\n");
        return -1; // 或者返回一个错误码
    }
    return  Q->front->Data;
}

int main() {
    //接收数字
    int num;
    scanf("%d", &num);
    //队列
    Queue Q = CreatQueue();
    //遍历
    for (int i = 0; i < num; i++) {
        char op[1000000];
        scanf("%s", op);
        if (strcmp(op, "push") == 0) {
            int x;
            scanf("%d", &x);
            push(Q, x);
        } else if (strcmp(op, "pop") == 0) {
            if (!IsEmpty(Q)) {
                printf("%d\n", pop(Q));
            } else {
                printf("error\n");
            }
        } else if (strcmp(op, "front") == 0) {
            if (!IsEmpty(Q)) {
                printf("%d\n", Front(Q));
            } else {
                printf("error\n");
            }
        }
    }
    return 0;
}

全部评论

相关推荐

爱吃肉的伊登在写日记:好棒,27届简历能做成这个样子,但是第一个项目感觉cover住难度还是不小的,特别是二面的时候肯定要对分布式系统设计这一块儿有高出正常面试者的水平才行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务