题解 | #【模板】队列#
【模板】队列
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; }