#define QDataType int
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);
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0
int QueueEmpty(Queue* q);
// 销毁队列
void QueueDestroy(Queue* q);
//打印队列
void QueueShow(Queue* q);
void QueueInit(Queue* q)
{
assert(q);
q->_front = NULL;
q->_rear = NULL;
}
void QueuePush(Queue* q, QDataType data)
{
assert(q);
QNode* s = (QNode*)malloc(sizeof(QNode));
assert(s);
s->_data = data;
s->_next = NULL;
if (q->_front == NULL)
{
q->_front = q->_rear = s;
}
else
{
q->_rear->_next = s;
q->_rear = s;
}
}
void QueueShow(Queue* q)
{
assert(q);
QNode* p = q->_front;
while (p != NULL)
{
printf("%d<--", p->_data);
p = p->_next;
}
printf("队尾\n");
}
void QueuePop(Queue* q)
{
assert(q);
if (q->_front !=NULL)
{
q->_front = q->_front->_next;
}
if (q->_front == NULL)
{
q->_rear = NULL;
//free(q);
}
}
QDataType QueueFront(Queue* q)
{
assert(q&&q->_front!=NULL);
return q->_front->_data;}
QDataType QueueBack(Queue* q)
{
assert(q&&q->_front != NULL);
return q->_rear->_data;
}
int QueueSize(Queue* q)
{
assert(q);
int sz = 0;
QNode*p = q->_front;
while (p!= NULL)
{
sz++;
p = p->_next;
}
return sz;
}
int QueueEmpty(Queue* q)
{
assert(q);
if (q->_front == NULL)
return 0;
else
return 1;
}
void QueueDestroy(Queue* q)
{
assert(q);
QNode*p = q->_front;
while (p != NULL)
{
q->_front = p->_next;
free(p);
p = q->_front->_next;
}
q->_front = q->_rear = NULL;
}
链式结构表示队列
最新推荐文章于 2023-10-21 12:13:24 发布