赞
踩
在介绍玩栈之后我们来介绍下队列基本结构
代码如下(示例):
// 链式结构:表示队列
typedef struct QListNode
{
struct QListNode* _pNext;
QDataType _data;
}QNode;
// 队列的结构
typedef struct Queue
{
QNode* _front;
QNode* _rear;
}Queue;
// 初始化队列
void QueueInit(Queue* q)
{
assert(q);
q->front = q->tail = NULL;
}
// 销毁队列
void QueueDestroy(Queue* q)
{
assert(q);
QueueNode* cur = q->front;
while (cur)
{
QueueNode* next = cur->next;
free(cur);
cur = next;
}
q->front = q->tail = NULL;
}
// 队尾入队列 void QueuePush(Queue* q, QDataType data) { assert(q); QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode)); newnode->data = data; newnode->next = NULL; if (q->front == NULL) { q->front = q->tail = newnode; } else { q->tail->next = newnode; q->tail = newnode; } }
// 队头出队列
void QueuePop(Queue* q)
{
assert(q);
assert(!QueueEmpty(q));
QueueNode* next = q->front->next;
free(q->front);
q->front = next;
if (q->front == NULL)
{
q->tail = NULL;
}
}
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0
int QueueEmpty(Queue* q)
{
assert(q);
return q->front == NULL;
}
// 获取队列头部元素 QDataType QueueFront(Queue* q) { assert(q);//断言防止传进来空指针 assert(!QueueEmpty(q));//断言防止队列空 return q->front->data; } // 获取队列队尾元素 QDataType QueueBack(Queue* q) { assert(q); assert(!QueueEmpty(q)); return q->tail->data; } // 获取队列中有效元素个数 int QueueSize(Queue* q) { assert(q); int n = 0; QueueNode* cur = q->front; while (cur) { cur = cur->next; n++; } return n; }
以上就是队列基础内容和操作,实际上栈和队列的实际应用还是很多,比如叫号机等等。那么队列和栈的常见题型下次见。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。