队列的链式实现

/************************************************************************/
/*                    队列的链式实现                                    */
/************************************************************************/
#include <stdio.h>
#include <STDLIB.H>



#define _ERROR 0
#define _OK 1




typedef int QElementType;
typedef int status;




typedef struct QNode
{
	QElementType data;
	struct QNode *next;//下一个节点
} QNode,*QueuePtr;

/*队列的数据抽象*/
typedef struct 
{
	QueuePtr front;//队首指针(出队)[指向准出队元素]
	QueuePtr rear;//队尾指针(入队)[指向刚入队元素]
}LinkQueue;





/*队列的初始化*/
status InitQueue(LinkQueue &Q)
{

	Q.front=NULL;
	Q.rear=NULL;
	return _OK;
}


/*判断队列是否为空*/
bool IsEmpty(LinkQueue Q)
{
	return Q.front==NULL;
}



/*入队*/
status InQueue(LinkQueue &Q,QElementType e)
{
	//构造节点
	QNode *ptrNode =(QNode*) malloc(sizeof(QNode));
	if(!ptrNode)
		return _ERROR;
	ptrNode->data=e;
	ptrNode->next=NULL;

	if(IsEmpty(Q))//判断队列是否为空
	{Q.front=Q.rear=ptrNode;
	return _OK;}	
	//如果不为空
	Q.rear->next=ptrNode;
	Q.rear = ptrNode;
	
	
	return _OK;
}



/*出队*/
status OutQueue(LinkQueue &Q,QElementType &e)
{
	if(IsEmpty(Q))
		return _ERROR;

	QNode *tempPtr = Q.front;
	e=tempPtr->data;

	Q.front = tempPtr->next;

	free(tempPtr);
	return _OK;
}




/*打印队列中的元素*/
void PrintQueue(LinkQueue Q)
{
	QNode *tempPtr = Q.front;
	while(tempPtr!=NULL)
	{
		printf("%d \n",tempPtr->data);
		tempPtr=tempPtr->next;
	}
}




void main()
{
	LinkQueue Q;

	//初始化
	InitQueue(Q);
	if(IsEmpty(Q))
		printf("队列此时为空\n");
	else
		printf("队列此时不为空\n");

	//入队列
	printf("入队列\n...........\n");
	InQueue(Q,1);
	InQueue(Q,2);
	InQueue(Q,3);
	InQueue(Q,4);

	//打印
	printf("打印队列元素\n");
	PrintQueue(Q);

	QElementType e;
	//出队列
	printf("出队列\n............\n");
	OutQueue(Q,e);
	printf("出元素%d\n",e);
	OutQueue(Q,e);
	printf("出元素%d\n",e);


	/*打印*/
	printf("打印队列元素\n");
	PrintQueue(Q);




	/*越界测试*/
	printf("越界测试\n..........\n");
	OutQueue(Q,e);
	OutQueue(Q,e);
	OutQueue(Q,e);
	OutQueue(Q,e);
	printf("正常\n");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值