头文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
struct BinaryTreeNode;
typedef struct BinaryTreeNode* QDataType;
typedef struct QListNode
{
struct QListNode* _next;
QDataType _data;
}QNode;
typedef struct Queue
{
QNode* _front;
QNode* _rear;
}Queue;
void QueueInit(Queue* q);
void QueuePush(Queue* q, QDataType data);
void QueuePop(Queue* q);
QDataType QueueFront(Queue* q);
QDataType QueueBack(Queue* q);
int QueueSize(Queue* q);
int QueueEmpty(Queue* q);
void QueueDestroy(Queue* q);
void PrintQueue(Queue* q);
接口实现
void QueueInit(Queue* q) {
q->_front = q->_rear = NULL;
}
void QueuePush(Queue* q, QDataType data) {
QNode* Newnode = (QNode*)malloc(sizeof(QNode));
if (Newnode == NULL) {
printf("Create Fail!\n");
exit(-1);
}
Newnode->_data = data;
Newnode->_next = NULL;
if (q->_front == NULL) {
q->_front = Newnode;
q->_rear = Newnode;
}
else {
q->_rear->_next = Newnode;
q->_rear = Newnode;
}
}
void QueuePop(Queue* q) {
assert(q);
assert(q->_front);
QNode* head_next = q->_front->_next;
free(q->_front);
q->_front = head_next;
if (head_next == NULL) {
q->_rear = NULL;
}
}
QDataType QueueFront(Queue* q) {
assert(q);
assert(q->_front);
return q->_front->_data;
}
QDataType QueueBack(Queue* q) {
assert(q);
assert(q->_rear);
return q->_rear->_data;
}
int QueueSize(Queue* q) {
assert(q);
if (q->_front == NULL) {
return 0;
}
QNode* cur = q->_front;
int count = 1;
while (cur != q->_rear) {
cur = cur->_next;
count++;
}
return count;
}
int QueueEmpty(Queue* q) {
assert(q);
return q->_front == NULL ? 1 : 0;
}
void QueueDestroy(Queue* q) {
assert(q);
QNode* cur = q->_front;
while (cur != NULL) {
QNode* next = cur->_next;
free(cur);
cur = next;
}
q->_front = q->_rear = NULL;
}
void PrintQueue(Queue* q) {
QNode* cur = q->_front;
while (cur != NULL) {
printf("%d ", cur->_data);
cur = cur->_next;
}
}