赞
踩
博主好久没发数据结构知识点的学习了,我们今天来看看队列的基础知识点吧,后几篇文章博主再来分享一些队列的实际应用。队列平时我们用的最多的是链队,顺序队列因为浪费空间,不推荐使用。这篇文章主要讲链队。好啦,废话不多说,直接上干货。
1.定义数据类型:
typedef struct Qnode
{
ElemType data;//其中数据域data为抽象元素类型
struct Qnode *next;//其中next为指针类型
}Qnode,*QueuePtr;//其中,Qnode为结点类型, QueuePtr:指向Qnode的指针类型
typedef struct
{ Qnode *front;//头指针
Qnode *rear;//尾指针
}LinkQueue;
2.初始化链队
typedef int Status;
Status InitQueue(LinkQueue *Q)
{
Q->front=(QueuePtr)malloc(sizeof(QNode));///给头尾指针分配内存,让队列中的头尾指针指向 同一个内存
Q->rear=Q->front;
if(!Q->front) exit(OVERFLOW);
Q->front->next=NULL;
return OK;
}
3.进队:
typedef int QElemType;
Status EnQueue(LinkQueue *Q,QElemType e)
{
QNode *p;
p=(QNode *)malloc(sizeof(QNode));
if(!p) exit(OVERFLOW);
p->data=e;//先赋值
p->next=NULL;
Q->rear->next=p;//再后移
Q->rear=p;
return OK;
}
4.出队:
typedef int Status;
Status DeQueue(LinkQueue *Q,QElemType *e)
{
QNode *p;
if(Q->front==Q->rear)
return ERROR;
p=Q->front->next;
*e=p->data;//先赋值
Q->front->next=p->next;//再后移
if(Q->rear==p)//到达队列末尾
Q->rear=Q->front;
free(p);
return OK;
}
5.打印队列元素:
void ShowQueueElement(LinkQueue Q)
{
QNode *p;
p=Q.front->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
6.求队列长度:
int QueueLength(LinkQueue Q)
{ int count=0;
QNode *p;
p=Q.front->next;
while(p!=NULL)
{ count++; p=p->next; }
return count;
}
7.获取队列头元素:
Status GetHead(LinkQueue Q,QElemType *e)
{ QNode *p;
p=Q.front;
if(Q.front==Q.rear)
return ERROR;
*e=p->next->data;
return OK;
}
8.清空队列:
Status ClearQueue(LinkQueue *Q)
{
QNode *p,*q;
p=Q->front->next;
Q->front->next=NULL;
while(p)
{
q=p->next;
free(p);
p=q;
}
Q->front=Q->rear;
return OK;
}
9.判断是否为空队列
Status QueueEmpty(LinkQueue *Q)
{ if(Q->front->next==NULL)
return TRUE;
else return FALSE;
}
10.销毁队列:
Status DestroyQueue(LinkQueue *Q)
{
while(Q->front)
{
Q->rear=Q->front->next;///队尾指针始终指向队头指针的下一个元素
free(Q->front);
Q->front=Q->rear;///调整队头指针
}
return OK;
}
好啦,今天关于队列的基础知识的分享就到这里啦。看到这,还不上机体验一下,hhh。
本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。