Dev条件下队列的链接储存结构和操作实现
- 格式:docx
- 大小:12.88 KB
- 文档页数:3
Dev条件下队列的链接储存结构和操作实现
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct QueueLk
{
struct sNode* front;
struct sNode* rear;
};
struct sNode
{
ElemType data;
struct sNode* next;
};
void InitQueue(struct QueueLk* HQ)//1 初始化队列
{
HQ->front=HQ->rear=NULL;
}
void EnQueue(struct QueueLk* HQ,ElemType x)//2向队列中插入一个元素{
struct sNode* newp;
newp=(struct sNode *)malloc(sizeof(struct sNode));
if(newp==NULL)
{
printf("内存动态空间用完,退出运行!\n");
exit(1);
}
newp->data=x;
newp->next=NULL;
if(HQ->rear==NULL)
HQ->front=HQ->rear=newp;
else
HQ->rear=HQ->rear->next=newp;
}
ElemType OutQueue(struct QueueLk* HQ)//3从队列中删除一个元素{
struct sNode* p;
ElemType temp;
if(HQ->front==NULL)
{
printf("队列为空,无法删除!\n");
exit(1);
}
temp=HQ->front->data;
p=HQ->front;
HQ->front=p->next;
if(HQ->front==NULL)
HQ->rear=NULL;
free(p);
return temp;
}
ElemType PeekQueue(struct QueueLk* HQ)//4读取队首元素
{
if(HQ->front==NULL)
{
printf("队列为空,无法删除!\n");
exit(1);
}
return HQ->front->data;
}
int EmptyQueue(struct QueueLk* HQ)//5检查链队是否为空
{
if(HQ->front==NULL) return 1;
else
return 0;
}
void ClearQueue(struct QueueLk* HQ)//清空链队里的所有元素,使之变为空队{
struct sNode* p=HQ->front;
while(p!=NULL)
{
HQ->front=HQ->front->next;
free(p);
p=HQ->front;
}
HQ->rear=NULL;
}
/*void Printf(struct QueueLk* HQ)
{
while(!EmptyQueue(HQ))
{
printf("%d ",OutQueue(HQ));
}
}*/
void Printf(struct QueueLk* HQ)
{
struct sNode* p=HQ->front;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
HQ->rear=NULL;
}
int main()
{
struct QueueLk Q;int i;
InitQueue(&Q);
int a[8]={8,7,6,5,4,3,2,1};
for(i=0;i<8;i++)
EnQueue(&Q,a[i]);
Printf(&Q);
return 0;
}。