//链式队列实现
#include<stdio.h>
#include<stdlib.h>
typedef struct Queue_LinkList
{
int data;
struct Queue_LinkList *next;
}Node,*pNode;
typedef struct Queue
{
pNode front,rear;
}Queue,*pQueue;
void Initqueue(pQueue); //初始化
int Isempty(pQueue); //判断队空
void Enqueue(pQueue,int*); //入队
int Dequeue(pQueue,int*); //出队
void Traverse(pQueue); //遍历
int main()
{
int val;
Queue s1;
Initqueue(&s1);
if(Isempty(&s1)) //判断队空
printf("队列为空!\n");
else printf("队列不空!\n");
printf("请输入入队元素:"); //入队1
scanf("%d",&val);
Enqueue(&s1,&val);
printf("请输入入队元素:"); //入队2
scanf("%d",&val);
Enqueue(&s1,&val);
printf("请输入入队元素:"); //入队3
scanf("%d",&val);
Enqueue(&s1,&val);
Traverse(&s1); //遍历
printf("\n");
if(Dequeue(&s1,&val)) //出队
printf("删除成功!删除的元素为:%d\n",val);
else printf("队空!出队失败!\n");
Traverse(&s1); //遍历
return 0;
}
//初始化
void Initqueue(pQueue ps1)
{
ps1->front=ps1->rear=(pNode)malloc(sizeof(Node));
if(ps1->front==NULL)
exit(-1);
else
{
ps1->front->next=NULL;
return;
}
}
//判断队空,空返回1,不空返回0
int Isempty(pQueue ps1)
{
if(ps1->front==ps1->rear)
return 1;
else return 0;
}
//入队,插入队尾,入队元素用val传递
void Enqueue(pQueue ps1,int *pVal)
{
pNode p;
p=(pNode)malloc(sizeof(Node));
p->data=*pVal;
p->next=NULL;
ps1->rear->next=p;
ps1->rear=p;
return;
}
//出队,出队元素用val传递,成功返回1,失败返回0
int Dequeue(pQueue ps1,int *pVal)
{
pNode p;
if(Isempty(ps1))
return 0;
else
{
p=ps1->front->next;
*pVal=p->data;
ps1->front->next=p->next;
if(ps1->rear==p)
ps1->rear=ps1->front;
free(p);
return 1;
}
}
//遍历,从队头遍历到队尾
void Traverse(pQueue ps1)
{
pNode p;
if(Isempty(ps1))
printf("所遍历队为空!\n");
else
{
printf("遍历结果:");
for(p=ps1->front->next;p!=ps1->rear;p=p->next) //循环条件为p!=ps1->rear,结束后尾结点没有输出
printf("%d ",p->data);
printf("%d ",p->data); //输出尾结点的数据
}
}
(C语言)链式队列的实现
最新推荐文章于 2024-03-11 22:33:08 发布