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

来源:互联网 发布:淘宝人气排名规则 编辑:程序博客网 时间:2024/04/30 04:13
#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;
}

0 0
原创粉丝点击