链队列的初始化,入队,出队,计算队的长度,遍历链队销毁队列

本文通过C语言实现链队列的初始化、入队、出队、判断队列是否为空、遍历队列、计算队列长度以及销毁队列等操作。详细展示了相关函数的定义和使用。
#include "stdio.h"
#include "stdlib.h"

typedef struct node{
int data;
struct node *next;
}*pnode;
typedef struct queue{
pnode front;
pnode rear;
}*pqueue;

//初始化队列
pqueue init(pqueue p)
{
p = (pqueue)malloc(sizeof(struct queue));
p->front = p->rear = NULL;
printf("初始化队列已经成功!\n");
return p;
}

//判断队列是否为空
void empty(pqueue p)
{
if (p->rear==NULL)
printf("队列为空!\n");
else
printf("队列不为空!\n");
}

//入队操作
int enqueue(pqueue p)
{
pnode q;
q = (pnode)malloc(sizeof(struct node));
printf("请输入你想入队的数据:\n");
scanf("%d",&q->data);
if (p->front == p->rear&&p->rear==NULL)
p->front = p->rear = q;
else
{
p->rear->next=q;
p->rear = p->rear->next;
p->rear->next = NULL;
}
return 0;
}

//出队操作
int delqueue(pqueue p)
{
if (p->rear==NULL)
printf("队列为空!\n");
else if ( p->front==p->rear&&p->rear != NULL)
{
printf("出队的数据是%d\n", p->front->data);
p->front = p->rear = NULL;
}
else
{
printf("你要出队的数据是:");
printf("%d\n",p->front->data);
p->front = p->front->next;
}
return 0;
}

//遍历链队
void show(pqueue p)
{
pnode f,r;
f = r = (pnode)malloc(sizeof(struct node));
f= p->front;
r = p->rear;
if (r == NULL)
printf("队列为空!\n");
else
while (f != NULL)
{
printf("%d ",f->data);
f = f->next;
}
printf("\n");
}

//计算链队的长度
void sumqueue(pqueue p)
{
int k = 0;
pnode f, r;
f = r = (pnode)malloc(sizeof(struct node));
f = p->front;
r = p->rear;
if (r == NULL)
printf("队列的长度是:0\n");
else
while(f!= NULL){
k++;
f = f->next;
}
printf("队列的长度是:%d\n",k);
}

//销毁队列
void desqueue(pqueue p)
{
if (p->front == p->rear == NULL)
printf("队列为空");
else if (p->rear == p->front != NULL)
free(p);
else
while (p->front != NULL)
{
free(p->front);
p->front = p->front->next;
}
printf("队列已经销毁!\n");
}
//主函数
int main()
{
pqueue p;
p = NULL;
int n;
do{
printf("***************************\n");
printf("1.初始化队列\n2.判断队列是否为空\n3.入队操作\n4.出队操作\n5.遍历队列中的元素\n6.输出队列的长度\n7.销毁队列\n8.退出程序\n");
printf("***************************\n");
printf("请输入你的选择!\n");
scanf("%d", &n);
switch (n){
case 1:
p=init(p);
break;
case 2:
empty(p);
break;
case 3:
enqueue(p);
break;
case 4:
delqueue(p);
break;
case 5:
show(p);
break;
case 6:
sumqueue(p);
break;
case 7:
desqueue(p);
break;
case 8:
break;
default :
printf("请输入正确的选择!\n");
}
} while (n != 8);
printf("程序已结束拜拜!\n");
return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值