MOOC 2.3 队列
1. 循环队列
// 队列的顺序存储实现 #define MaxSize <存储数据元素的最大个数> struct QNode { ElementType Data[MaxSize]; int rear; int front; }; typedef struct QNode *Queue; // 1. 入队 void AddQ(Queue PtrQ, ElementType item) { if((PtrQ->rear + 1) % MaxSize == PtrQ->front) { printf("队列满"); return ; } PtrQ->rear = (PtrQ->rear + 1) % MaxSize; PtrQ->Data[PtrQ->rear] = item; } // 2. 出队 ElementType DeleteQ(Queue PtrQ) { if(PtrQ->front == PtrQ->rear) { printf("队列空"); return REEOR; } else { PtrQ->front = (PtrQ->front + 1) % MaxSize; return PtrQ->Data[PtrQ->front]; } }
2. 链式队列
// 队列的链式存储 struct Node { ElementType Data; struct Node *Next; }; struct QNode { struct Node *rear; struct Node *front; }; typedef struct QNode *Queue; Queue PtrQ; ElementType DeleteQ(Queue PtrQ) { struct Node *FrontCell; ElementType FrontElem; if(PtrQ->front == NULL) { printf("队列为空"); return ERROR; } FrontCell = PtrQ->front; if(PtrQ->front == PtrQ->rear) // 队列只有一个元素 { PtrQ->front = PtrQ->rear = NULL; // 删除后队列值为空 } else { PtrQ->front = PtrQ->front->Next; } FrontElem = FrontCell->Data; free(FrontCell); // 释放被删除的结点空间 return FrontElem; } void AddQ(Queue PtrQ, ElementType item) { struct Node node; node = (struct Node *)malloc(sizeof(struct Node)); node->Data = item; node->Next = PtrQ->front->Next; PtrQ->front->Next = node; }