代码帖
头文件 Queue.h
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
//数组而言并不合适,对头出数据需要挪动顺序
//单链表更为合适,尾插头删
typedef int QDataType;
typedef struct QueueNode
{struct QueueNode* next;QDataType data;
}QNode;typedef struct Queue
{QNode* head;QNode* tail;
}Queue;void QueueInit(Queue* pq);
void QueueDestory(Queue* pq);
//队尾入
void QueuePush(Queue* pq,QDataType x);
//队头出
void QueuePop(Queue* pq);QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
int QueueSize(Queue* pq);
bool QueueEmpty(Queue* pq);
CPP文件 Queue.cpp
#include"Queue.h"
void QueueInit(Queue* pq)
{assert(pq);pq->head=pq->tail = NULL;
}void QueueDestory(Queue* pq)
{assert(pq);QNode* cur = pq->head;while (cur){QNode* next = cur->next;free(cur);cur = next;}pq->head = pq->tail = NULL;
}//队尾入
void QueuePush(Queue* pq, QDataType x)
{assert(pq);QNode* newnode =(QNode*) malloc(sizeof(QNode));if (newnode == NULL){cout << "malloc fail!" << endl;exit(-1);}newnode->data = x;newnode->next = NULL;if (pq->tail == NULL){pq->head = pq->tail = newnode;}else{pq->tail->next = newnode;pq->tail = newnode;}
}//队头出
void QueuePop(Queue* pq)
{assert(pq);assert(pq->head);//注意几个节点!if (pq->head->next == NULL){free(pq->head);pq->head = pq->tail = NULL;//防止野指针}else{QNode* next = pq->head->next;free(pq->head);pq->head = next;}
}QDataType QueueFront(Queue* pq)
{assert(pq);assert(pq->head);return pq->head->data;}
QDataType QueueBack(Queue* pq)
{assert(pq);assert(pq->head);return pq->tail->data;
}int QueueSize(Queue* pq)
{assert(pq);int size = 0;QNode* cur = pq->head;while (cur){++size;cur = cur->next;}return size;
}
bool QueueEmpty(Queue* pq)
{assert(pq);return pq->head == NULL;
}
测试文件 Test.cpp
#include"Queue.h"void TestQueue()
{Queue q;QueueInit(&q);}int main()
{//TestStack();Queue q;QueueInit(&q);QueuePush(&q, 1);QueuePush(&q, 2);QueuePush(&q, 3);QueuePush(&q, 4);QueuePush(&q, 5);while (!QueueEmpty(&q)){cout << QueueFront(&q) << endl;QueuePop(&q);}QueueDestory(&q);return 0;}