题解 | #【模板】队列1#

#include<stdio.h>
#include<stdlib.h>
#include<string.h>//调用strcmp函数头文件
#define LEN sizeof(QNode)//定义一个宏,方便
typedef struct Queue {//链表结点
    int data;
    struct Queue* next;
} QNode, *Queue;
typedef struct {//定义头指针和尾指针结构体,方便调用指针
    QNode* front;
    QNode* rear;
} LinkQueue;

void Create_Queue(LinkQueue* Q) {//建立一个带头结点的链表
    Q->front = Q->rear = (Queue)malloc(LEN);
    Q->front->next=NULL;
}

void push(LinkQueue* Q) {//入队
    int x;
    QNode* p;
    //printf("\n请输入插入队列的数据x:\t");
    scanf("%d", &x);
    p = (Queue)malloc(LEN);
    p->data = x;
    p->next = NULL;
    Q->rear->next = p;
    Q->rear = p;
}

void pop(LinkQueue* Q) {//队头出队
    QNode* p;
    if (Q->front == Q->rear) {
        printf("error\n");
        return ;
    }
    p = Q->front->next;
    printf("%d\n", p->data);
    Q->front->next=p->next;
    if(Q->rear==p){
        Q->rear=Q->front;
    }
    free(p);//释放已出队元素空间
}

void front(LinkQueue* Q) {//获取队头,不出队
    if (Q->front == Q->rear) {
        printf("error\n");
        return ;
    }
    printf("%d\n", Q->front->next->data);
}

int main() {
    LinkQueue Q;//定义一个指针结构体类型,方便调用头尾指针
    int n;//记录操作次数
    //printf("\n请输入操作次数n:\t");
    scanf("%d", &n);
    Create_Queue(&Q);
    while (n && n >= 1 && n <= 100000) {
        char a[10];//每次循环都重新初始化字符数组a,以及标记flag
        int flag = 0;//标记为0,说明输入操作函数错误
        //printf("\n请输入操作函数:\t");
        scanf("%s", a);
        if (strcmp("push", a) == 0) {
            push(&Q);
            flag = 1;
        }
        if (strcmp("pop", a) == 0) {
            pop(&Q);
            flag = 1;
        }
        if (strcmp("front", a) == 0) {
            front(&Q);
            flag = 1;
        }
        if (!flag) {
            printf("\n输入操作函数错误!");
        }
        n--;
    }
    return 0;
}
全部评论

相关推荐

晗江雪:其实我只是觉得你们导员说的很好笑
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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