链队列C语言实现

编写一个程序,实现链队列的各种基本运算,
(MAXQSIZE = 5),并在此基础上设计一个主程序完成如下功能:
(1)初始化队列 q;
(2)判断队列 q 是否为空;
(3)依次进队列元素 1, 12, -10; (4)出队一个元素,并输出该元素;
(5)输出队列的长度(元素个数);
(6)依次进队元素 13, -12, 10; (7)输出队列长度;
(8)输出出队序列

#include<stdio.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 5
typedef  int QElemType;
typedef  int Status;
//链队的存储结构
typedef struct QNode
{
	QElemType data;     //数据域
	struct QNode *next;  //指针域
}QNode,*QueuePtr;
typedef struct
{
	QueuePtr front;      //队头指针
	QueuePtr rear;      //队尾指针
}LinkQueue;
//链队的初始化
Status InitQueue(LinkQueue &Q)
{
	Q.front = Q.rear = new QNode;  //生成新结点作为队头结点,队头队尾指针指向此结点
	Q.front->next = NULL;    //头结点的指针域置空
	return OK;
}
//判空
Status QueueEmpty(LinkQueue Q)
{
	if (Q.front == Q.rear) return ERROR;
	else return OK;
}
//入队
Status EnQueue(LinkQueue &Q, QElemType e)
{
	QueuePtr p;
	p = new QNode;    //生成新结点
	p->data = e;      //赋值e
	p->next = NULL;    //插入队尾,后插法
	Q.rear->next = p;
	Q.rear = p;
	return OK;
}
//出队
Status DeQueue(LinkQueue &Q, QElemType &e)
{
	if(Q.front == Q.rear) return ERROR;  //判空
	QueuePtr p;   
	p = Q.front->next;  //p标记队头结点
	e = p->data;     //队头元素赋给e
	Q.front->next = p->next;
	if (Q.rear == p)Q.rear = Q.front;   //最后一个元素被删除
	delete p;   //删除队头结点
	return OK;
}
//求队的长度
int QueueLength(LinkQueue Q)
{
	int n = 0;   //记录长度
	if (Q.front == Q.rear) return ERROR;  //判空
	while (Q.front != Q.rear)
	{
		Q.front = Q.front->next;   //顺沿
		n++;
	}
	return n;
}

int main()
{
	LinkQueue Q; QElemType e; int n = 3;
	InitQueue(Q);                   //初始化队Q
	//判空
	printf("空为0,不空为1:%d\n", QueueEmpty(Q));
	//入队
	printf("依次进队元素:-1 12 10\n");
	scanf_s("%d", &e);
	EnQueue(Q, e);
	for (int i = 0; i < n-1; i++)
	{
		scanf_s("%d", &e);
		EnQueue(Q, e);
	}
	//出队
	printf("出队一个元素\n");
	DeQueue(Q, e);
	printf("%d\n", e);
	//求队长
	printf("队列长度:%d\n", QueueLength(Q));
	//入队
	printf("依次进队元素 -3 2 -10\n");
	for (int i = 0; i < 3; i++)
	{
		scanf_s("%d", &e);
		EnQueue(Q, e);
	}
	printf("队列长度:%d\n", QueueLength(Q));
	//出队并输出
	while (QueueEmpty(Q))
	{
		DeQueue(Q,e);
		printf("%5d", e);
	}
}
  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值