Queue.h
#ifndef _QUEUE_H_ #define _QUEUE_H_ #includetypedef int Item; #define MAXQUEUE 10 typedef struct node { Item item; struct node* next; }Node; typedef struct queue { Node* front; //记录头部 Node* rear; //记录尾部 int items; //记录项数 }Queue; //队列初始化为空 void InitializeQueue(Queue* pq); //检查队列是否以满 bool QueueIsFull(const Queue* pq); //检查队列是否为空 bool QueueIsEmtpy(const Queue* pq); //确定队列中的项数 int QueueItemCount(const Queue* pq); //在队列末尾添加项 bool EnQueue(Item item, Queue* pq); //从队列的开头删除项 bool DeQueue(Item* pitem, Queue* pq); //清空队列 void EmptyTheQueue(Queue* pq); #endif
Queue.cpp
#include#include #include "queue.h" static void CopyToNode(Item item, Node* pn); static void CopyToItem(Node* pn, Item* pi); void InitializeQueue(Queue* pq) //初始化 { pq->front = NULL; pq->rear = NULL; pq->items = 0; } bool QueueIsFull(const Queue* pq) //判断是否已满 10 { return pq->items == MAXQUEUE; } bool QueueIsEmtpy(const Queue* pq) //检查队列是否为空 { return pq->items == 0; } int QueueItemCount(const Queue* pq) //确定队列中的项数 { return pq->items; } bool EnQueue(Item item, Queue* pq) //在末尾添加项 item=1; { Node* pnew = {}; if (QueueIsFull(pq)) return false; pnew = (Node*)malloc(sizeof(Node)); if (pnew == NULL) { fprintf(stderr, "Unable to allocate memory!n"); exit(1); } CopyToNode(item, pnew); pnew->next == NULL; if (QueueIsEmtpy(pq)) { pq->front = pnew; } else { pq->rear->next = pnew; } pq->rear = pnew; pq->items++; return true; } bool DeQueue(Item* pitem, Queue* pq) //从队列开头删除项 { Node* pt = {}; if (QueueIsEmtpy(pq)) return false; CopyToItem(pq->front, pitem); pt = pq->front; pq->front = pq->front->next; free(pt); pq->items--; if (pq->items == 0) pq->rear = NULL; return true; } void EmptyTheQueue(Queue* pq) //清空队列 { Item dummy; while (!QueueIsEmtpy(pq)) DeQueue(&dummy, pq); } void CopyToNode(Item item, Node* pn) //拷贝到节点 { pn->item = item; } void CopyToItem(Node* pn, Item* pi) //拷贝到项目 { *pi = pn->item; }
UseQueue.cpp
#include#include "queue.h" int main(void) { char ch; Item temp; Queue line; InitializeQueue(&line); puts("Testing the Queue interface. Type a to add a value,"); puts("type d to delete a value, and type q to quit."); while ((ch = getchar()) != 'q') { if (ch != 'a' && ch != 'd') { printf("incorrect inputn"); continue; } if (ch == 'a') { printf("Integer to add: "); scanf_s("%d", &temp); if (!QueueIsFull(&line)) { printf("Putting %d into queuen", temp); EnQueue(temp, &line); } else puts("Queue is full!"); } else { if (QueueIsEmtpy(&line)) puts("Noting to delete!"); else { DeQueue(&temp, &line); printf("Removing %d from queuen", temp); } } printf("%d items in queuen", QueueItemCount(&line)); puts("Type a to add, d to delete, q to quit:"); } EmptyTheQueue(&line); puts("bye!"); return 0; }



