天气蛮好
姥姥写的空一个内存的队列,front指向队首前一位,rear指向队尾。
有意思的是打印时需要注意分类讨论:
#include<stdio.h> #include<stdlib.h> #define maxsize 10 //队列只能存储maxsize-1个数据 typedef int position; //rear指向队列尾,刚刚插入的元素 //front指向第一个元素的前一位 //front指向的内存永不存放有效数据 当front等于rear时队列为空 typedef struct { int* data; position front, rear; }queue,*pqueue; pqueue createqueue() { pqueue Q = (pqueue)malloc(sizeof(queue)); Q->data = (int*)malloc(maxsize * sizeof(int)); Q->front = Q->rear = 0; return Q; } int isfull(pqueue Q) { return ((Q->rear + 1) % maxsize == Q->front); } int isempty(pqueue Q) { return (Q->front == Q->rear); } int addq(pqueue Q, int elem) { if (isfull(Q)) { printf("满了"); return 0; } else { Q->rear = (Q->rear + 1) % maxsize; Q->data[Q->rear] = elem; return 1; } } int deleteq(pqueue Q) { if (isempty(Q)) { printf("空的"); return 0; } else { Q->front = (Q->front + 1) % maxsize; return Q->data[Q->front]; } } void print(pqueue Q) { if (Q->rear > Q->front) { for (int i = Q->front + 1; i <= Q->rear; i++) { printf("%d ", Q->data[i]); if (i == Q->rear)printf("\n"); } } else { for (int i = Q->front + 1; i < maxsize; i++) { printf("%d ", Q->data[i]); } for (int i = 0; i <= Q->rear; i++) { printf("%d ", Q->data[i]); if (i == Q->rear)printf("\n"); } } } int main() { pqueue Q = createqueue(); for (int i = 0; i < maxsize-1; i++) { addq(Q, i); } print(Q); deleteq(Q); print(Q); deleteq(Q); print(Q); addq(Q, 9); print(Q); }
摆了摆了明天再写