前一篇,链表:队列的实现,在使用时必须确定开辟的元素个数,缺点:元素空间开辟少了,不够用;元素空间开辟多了,浪费空间。
优化后的队列:实际数据个数大于开辟的元素个数时,链表会自动扩充队列的长度,再也不用担心队列被填满了。
修改后的部分:
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;
}