队列与栈不同,他是尾进头出,因此他的输出内容是固定的;
下面是一些队列的基本运用
首先,因为队列的特殊性,需要知道链表的头尾节点,要想改变链表的数据,则需要传递二级指针,为了简化函数的参数,定义一个新结构体,其包含着链表的头和尾以及size(视为链表长度)
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}Qnode;
typedef struct Queue
{
//头
Qnode* phead;
//尾
Qnode* ptail;
int size;
}Queue;
1 初始化
将头和尾都置为空,链表长度置为0
void QueueInit(Queue* pq)
{
assert(pq);
pq->phead = NULL;
pq->ptail = NULL;
pq->size = 0;
}
2 销毁
与链表的销毁一致,遍历链表依次销毁,定义一个cur来遍历链表,next来保存cur->next;然后释放cur,将cur=next;如此重复即可销毁,此时将头和尾置空,避免造成野指针,size置0;
void QueueDestroy(Queue* pq)
{
assert(pq);
Qnode* cur = pq->phead;
while (cur)
{
Qnode* next = cur->next;
free(cur);
cur = next;
}
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
3 队尾插入
先malloc一个newnode,如果队列此时没人即队尾为空(ptail=null),则直接插入,;有人,则先插入队尾,让newnode成为一个新的队尾;最后size++,记录队列长度;
void QueuePush(Queue* pq, QDataType x)
{
Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
if (newnode == NULL)
{
perror("malloc fail");
return;
}
newnode->data = x;
newnode->next = NULL;
assert(pq);
//队尾为空说明队列为空
if (pq->ptail==NULL)
{
pq->phead = pq->ptail = newnode;
}
else
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
pq->size++;
}
4 队头删除
队头删除考虑的比较多,不能传递空指针且队头不能是空指针,如果队列长度为1即phead->next=NULL,则可以直接free掉,同时将phead和ptail置为NULL;队列长度大于一的话,则可以定义一个next用来记录phead->next,free掉phead后,next成为新的头,phead=next;最后size--;
//队头删除
void QueuePop(Queue* pq)
{
assert(pq);
assert(pq->phead);
if (pq->phead ->next==NULL)
{
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else
{
Qnode* next = pq->phead->next;
free(pq->phead);
pq->phead = next;
}
pq->size--;
}
5 求队列长度
直接return size
QDataType QueueSize(Queue* pq)
{
assert(pq);
assert(pq->phead);
return pq->size;
}
6 找队头队尾的数据
直接返回phead和ptail(不能为空)
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(pq->phead);
return pq->phead->data;
}
QDataType QueueBack(Queue* pq)
{
assert(pq);
assert(pq->ptail);
return pq->ptail ->data;
7 判断队列是否为空
如果size=0,则为空,不为0则不为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->size == 0;
}
1258

被折叠的 条评论
为什么被折叠?



