链表:队列的实现(优化后)

       前一篇,链表:队列的实现,在使用时必须确定开辟的元素个数,缺点:元素空间开辟少了,不够用;元素空间开辟多了,浪费空间。


       优化后的队列:实际数据个数大于开辟的元素个数时,链表会自动扩充队列的长度,再也不用担心队列被填满了。


修改后的部分:

void QUEUE::Push(int Num)      //Push a number into the QUEUE
{
	if (Centrol != Head)
	{
		Centrol->Date = Num;
		Centrol = Centrol->pf;
	}
	else
	{
		Centrol->pf=Head = (struct _QUEUE*)malloc(sizeof(struct _QUEUE));
		Head->pb = Centrol;
		Centrol->Date = Num;
		Centrol = Centrol->pf;
	}
}

以下是源码:

#pragma once
#include<stdlib.h>
struct _QUEUE
{
	struct _QUEUE *pf;
	struct _QUEUE *pb;
	int Date;
};
class QUEUE
{
private:
	

	_QUEUE *Head,*Button,*CpyButton,*Next,*Ahead,*Centrol;
public:
	QUEUE(int Num = 15)
	{
		
		for (int i = 0; i < Num+1; ++i)
		{
			Next = (struct _QUEUE*)malloc(sizeof(struct _QUEUE));
			if (i == 0)
			{
				Head = Ahead = Next;
				//Head->pf = nullptr;
			}
			else
			{
				Ahead->pb = Next;
				Next->pf = Ahead;
				Ahead = Next;

			}
			CpyButton=Centrol = Button = Next;
		}
	}
	
	void Push(int Num);      //Push a number into the QUEUE
	int PopBotton();            //Get a number from the Button of QUEUE
	bool IsEmpty();          //To judge whether the QUEUE is empty .If so,return true,else,return false.
	
};
void QUEUE::Push(int Num)      //Push a number into the QUEUE
{
	if (Centrol != Head)
	{
		Centrol->Date = Num;
		Centrol = Centrol->pf;
	}
	else
	{
		Centrol->pf=Head = (struct _QUEUE*)malloc(sizeof(struct _QUEUE));
		Head->pb = Centrol;
		Centrol->Date = Num;
		Centrol = Centrol->pf;
	}
}
int QUEUE::PopBotton()           //Get a number from the Button of QUEUE
{
	Centrol = Centrol->pb;
	int  ButtonNumber = Button->Date;
	while (true)
	{
		if (CpyButton == Centrol)
		{
			
			CpyButton->Date = 0;
			CpyButton = Button;
			break;
		}
		else
		{
			CpyButton->Date = CpyButton->pf->Date;
			CpyButton = CpyButton->pf;
		} }
	
	return  ButtonNumber;
}
bool QUEUE::IsEmpty()          //To judge whether the QUEUE is empty .If so,return true,else,return false.
{
	if (Centrol == Button || Centrol != Head)
		return true;
	else
		return false;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值