1.队列的概念及结构
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出性质。
入队列:进行插入操作的一端称为队尾 。
出队列:进行删除操作的一端称为队头。
2.队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。
我们会发现他们入队的效果其实一样,但是出队就不一样,数组需要将后面的每一个元素都往前挪动,而链表就是改变头结点的位置就可以了。
2.1初始化队列
初始化队列就是将队头队尾置空就可以了。
//链式结构:表示队列
typedef int QDataType;
typedef struct QListNode
{
struct QListNode* next;
QDataType data;
};
//队列的结构
typedef struct Queue
{
struct Queue* head;
struct Queue* tail;
}Queue;
//初始化队列
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
}
2.2队尾入队列
//队尾入队列
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
assert(newnode);
newnode->data = x;
newnode->next = NULL;
if (pq->tail == NULL)
{
assert(pq->head == NULL);
pq->head = pq->tail = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
}
2.3队头出队列
//队头出队列
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->head && pq->tail);
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;
}
}
2.4获取队列头部元素
获取队列头部元素就是将头部元素的值给返回回来:
//获取队列头部元素
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(pq->head);
return pq->head->data;
}
2.5获取队列尾部元素
获取队列尾部元素就是将尾部元素的值给返回回来:
//获取队列头部元素
QDataType QueueBack(Queue* pq)
{
assert(pq);
assert(pq->tail);
return pq->tail->data;
}
2.6获取队列中有效元素个数
//获取队列中有效元素个数
int QueueSize(Queue* pq)
{
assert(pq);
int count = 0;
QNode* cur = pq->head;
while (cur)
{
cur = cur->next;
count++;
}
return count;
}
2.7判断队列是否为空
//判断队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
2.9队列的销毁
//队列的销毁
void QueueDestory(Queue* pq)
{
assert(pq);
assert(pq->head);
QNode* cur = pq->head;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
以上如有错误,请批评指正!!!