队列的初始化
void QueueInit(Queue* pq)
{
if (pq == NULL)
{
return;
}
pq->head = pq->tail = NULL;
}
队列的销毁
void QueueDestroy(Queue* pq)
{
QNode* node = pq->head;
while (node!= pq->tail)
{
QNode* cur = node->next;
free(node);
node = cur;
}
pq->head = NULL;
pq->tail = NULL;
}
入队
void QueuePush(Queue* pq, QDataType x)
{
if (pq == NULL)
{
return;
}
QueueNode* newNode = new QueueNode;
newNode->next = NULL;
newNode->data = x;
if (pq->tail == NULL)
{
pq->head = pq->tail = newNode;
}
else
{
pq->tail->next = newNode;
pq->tail = newNode;
}
}
出队
void QueuePop(Queue* pq)
{
if (pq == NULL)
{
return;
}
if (pq->tail == NULL)
{
return;
}
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = NULL;
pq->tail = NULL;
return;
}
QNode* newNode = pq->head;
pq->head = newNode->next;
free(newNode);
newNode = NULL;
}
取得队头元素
QDataType QueueFront(Queue* pq)
{
if (pq == NULL)
{
return NULL;
}
if (pq->head != NULL)
{
return pq->head->data;
}
return NULL;
}
取得队尾元素
QDataType QueueBack(Queue* pq)
{
if (pq == NULL)
{
return NULL;
}
if (pq->tail != NULL)
{
return pq->tail->data;
}
return NULL;
}
队列大小
int QueueSize(Queue* pq)
{
int count = 0;
if (pq == NULL)
{
return NULL;
}
QNode* newNode = pq->head;
while (newNode)
{
newNode = newNode->next;
count++;
}
return count;
}
判断队列是否为空
bool QueueEmpty(Queue* pq)
{
if (pq == NULL)
{
return true;
}
return pq->tail == NULL;
}
测试
void test()
{
Queue q;
QueueInit(&q);
QueuePush(&q,1);
QueuePush(&q, 3);
QueuePush(&q, 5);
QueuePush(&q, 7);
QueuePush(&q, 8);
QueuePush(&q, 11);
int size = QueueSize(&q);
cout << "队列的大小:" << size << endl;
while (!QueueEmpty(&q))
{
cout<< QueueFront(&q)<< " ";
QueuePop(&q);
}
QueueDestroy(&q);
}