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