目录
1.队列的概念及结构
2.队列的实现
2.1队列结构定义
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct Queue
{
QNode* head;
QNode* tail;
}Queue;
2.2队列的初始化及销毁
//队列初始化
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
//队列销毁
void QueueDestroy(Queue* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur)
{
QNode* del = cur;
cur = cur->next;
free(del);
}
pq->head = pq->tail = NULL;
}
2.3数据入队
//数据入队
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
else
{
newnode->data = x;
newnode->next = NULL;
}
//空队列时插入
if (pq->tail == NULL)
{
pq->head = pq->tail = newnode;
}
//非空队列时插入
else
{
pq->tail->next = newnode;//链接新元素
pq->tail = newnode;//更新队尾
}
}
2.4数据出队
//数据出队
void QueuePop(Queue* pq)
{
assert(pq);
//空队列不能进行出队操作
assert(!QueueEmpty(pq));
//队列中只有一个元素
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QNode* del = pq->head;
pq->head = pq->head->next;
free(del);
del = NULL;
}
}
2.5访问队头数据
//访问队头数据
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
2.6访问队尾数据
//访问队尾数据
QDataType QueueBack(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
2.6判断队列是否为空
//判断队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
/*if (pq->tail == pq->head == NULL)
{
return true;
}
else
{
return false;
}*/
return pq->head == NULL && pq->tail == NULL;
}
2.7求队列的大小
//求队列的大小
int QueueSize(Queue* pq)
{
assert(pq);
int size = 0;
QNode* cur = pq->head;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
2.7打印队列
//打印队列
void QueuePrint(Queue* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}