题解 | #【模板】队列#

【模板】队列

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 队列节点结构体
typedef struct node {
    int val;
    struct node *next;
} *Node, node;

// 队列指针结构体
typedef struct queue {
    struct node *front;
    struct node *rear;
    int count;
} *Queue, queue;

void push(Queue *q, int x) {
    Queue p = *q;
    Node s = (Node) malloc(sizeof(node));
    s->val = x;
    s->next = NULL;
    p->rear->next = s;
    p->rear = s;
}

void pop(Queue *q) {
    Queue p = *q;
    if (p->front->next == NULL) {
        printf("error\n");
        return;
    }
    printf("%d\n", p->front->next->val);

    // 修改出队后队头 / 尾指针
    if (p->front->next->next != NULL) {
        p->front->next = p->front->next->next;
    } else {
        // 队首元素出队后,队列为空,将队头,队尾指针的下一个置为空
        p->rear = p->front;
        p->front->next = NULL;
    }
}

void front(Queue q) {
    if (q->front->next == NULL) {
        printf("error\n");
        return;
    }
    printf("%d\n", q->front->next->val);
}

int main() {

    Queue q = (Queue) malloc(sizeof(queue));
    Node p = (Node) malloc(sizeof(node));
    p->next = NULL;
    q->front = q->rear = p;

    int n;
    scanf ("%d", &n);
    for (int i = 0; i < n; ++i) {
        char ope[10];
        scanf("%s", ope);
        if (strcmp(ope, "push") == 0) {
            int x;
            scanf("%d", &x);
            push(&q, x);
        } else if (strcmp(ope, "pop") == 0) pop(&q);
        else if (strcmp(ope, "front") == 0) front(q);
    }

    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 15:08
点赞 评论 收藏
分享
05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
陈逸轩1205:才105 哥们在养生呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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