编写一个程序algo3-3.cpp,实现顺序环形队列的各种基本运算,并在此基础上设计一个主程序
一、定义一个队列的结构体
typedef int QueueNodeTypeData; // 队列节点
typedef struct QueueNode // 队列节点
{
QueueNodeTypeData data;
struct QueueNode* next;
}QueueNodeType;
typedef struct Queue // 链式结构表示队列,队列已经不再是单独的节点,是一堆节点的集合
{
QueueNodeType* tail; // 队列中的尾节点
QueueNodeType* head; // 队列中的头节点
int size; // 队列中存储的元素的数量
}Queue;
二、初始化队列
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
pq->size = 0;
}
三、入队操作
入队也分两种情况:
当队列中有空的时候
队列已经满了,此时需要将队列的容量增大,我们按照原来容量的两倍去增大,
void QueuePush(Queue* pq, QueueNodeTypeData x)
{
assert(pq);
QueueNodeType* newNode = (QueueNodeType*)malloc(sizeof(QueueNodeType));
newNode->data = x;
newNode->next = NULL;
if (pq->head == NULL)
{
pq->head = pq->tail = newNode; // 只有一个节点
}
else
{
pq->tail->next = newNode; // 新节点挂到链表尾部
pq->tail = newNode;
}
++pq->size;
}
四、出队操作
出队需要获得队列头部的指针,并将头部节点删除
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->head);
QueueNodeType* next = NULL;
next = pq->head->next;
free(pq->head);
pq->head = next;
--pq->size;
}
五、判断队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->size == 0;
}
六、销毁队列
void QueueDestroy(Queue* pq)
{
assert(pq);
while (pq->head)
{
QueueNodeType* next = pq->head->next;
free(pq->head);
pq->head = next;
}
pq->tail = NULL;
}
七、主程序
int main()
{
Queue q;
QueueInit(&q); // 初始化
QueuePush(&q, 1); // 入队操作
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
while (!QueueEmpty(&q)) // 出队操作
{
printf("%d ", q.head->data);
QueuePop(&q);
}
printf("\n");
QueueDestroy(&q); // 销毁队列
return 0;
}
以上,就是如何编写一个程序来实现顺序环形队列的基本运算.