数据结构基础代码05链队列

#include<iostream>
#include<stdlib.h>
typedef int ElemType;
using namespace std;
#define MaxSize 50

typedef struct LinkNode{
	ElemType data;
	struct LinkNode* next;
}LinkNode;

typedef struct{
	LinkNode* front,*rear;
}LinkQueue;
//初始化
void InitQueue(LinkQueue &Q)
{	
	Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
	Q.front->next = NULL;	
} 
//判断队空
bool isEmpty(LinkQueue Q)
{
	if(Q.front==Q.rear)
		return true;
	else
		return false;
}
//入队(链队列不用考虑队满) 
void EnQueue(LinkQueue &Q,ElemType x)
{
	LinkNode *s=(LinkNode*)malloc(sizeof(LinkNode));
	s->data=x;
	s->next=NULL;
	Q.rear->next=s;
	Q.rear=s;
}
//出队
bool DeQueue(LinkQueue &Q,ElemType &x)
{
	//空队列 
	if(Q.rear==Q.front)
	{
		return false;
	}
	LinkNode *p=Q.front->next;
	x=p->data;
	Q.front->next=p->next;
	if(Q.rear==p)
	{
		Q.rear=Q.front;
	}
	free(p);
	return true;
}
int main()
{
	LinkQueue hahaha;
	InitQueue(hahaha);
	if(isEmpty(hahaha))
	{
		cout<<"this queue is empty"<<endl;
	}
	//验证入队 
	for(int i=0;i<5;i++)
	{
		EnQueue(hahaha,i);
	}
	if(isEmpty(hahaha))
	{
		cout<<"this queue is empty"<<endl;
	}
	else
	{
		cout<<"this queue is not empty"<<endl;
	}
	LinkNode* temp = hahaha.front->next;//temp指向hahaha的队头指针 
	while(temp)
	{
		cout<<temp->data<<endl;//输出temp当前所指的节点的数据域 
		temp = temp->next;//temp向后循环 
	} 
	
	//验证出队
	for(int i=0;i<5;i++)
	{
		int x;
		DeQueue(hahaha,x);
		temp = hahaha.front->next;//temp指向hahaha的队头指针 
		while(temp)
		{
			cout<<temp->data<<" ";//输出temp当前所指的节点的数据域 
			temp = temp->next;//temp向后循环 
		} 
		cout<<endl;
	}
	if(isEmpty(hahaha))
	{
		cout<<"this queue is empty"<<endl;
	}
	else
	{
		cout<<"this queue is not empty"<<endl;
	}
} 

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值