设计你循环队列的实现。 循环队列是线性数据结构,根据先进先出(FIFO )原则运行,队列末尾连接在最前面,形成循环。 也被称为“环形缓冲区”。
循环队列的一个优点是可以使用此队列之前使用的空间。 在普通队列中,如果队列已满,则即使队列前面有空间,也不能插入以下元素: 但是,循环队列允许您使用这些空间存储新值。
你的实现应该支持以下操作。
将mycircularqueue(k ) :构造函数和队列长度设置为k。 Front:从团队开头获取元素。 如果队列为空,则返回-1。 Rear:获取团队的最后一个元素。 如果队列为空,则返回-1。 enqueue(value ) :将元素插入循环队列中。 如果插入成功,则返回照片。 deQueue ) ) :从循环队列中删除元素。 如果删除成功,则返回照片。 isEmpty ) )检查:循环队列是否为空。 isFull ) )检查:循环队列是否已满。示例:
mycircularqueuecircularqueue=newmycircularqueue (3; //长度3circularqueue.enqueue(1); //truecircularqueue.enqueue(2 (返回2; 返回//truecircularqueue.enqueue(3)//truecircularqueue.enqueue(4)返回false,队列返回circularQueue.Rear (; 3返回3circularQueue.isFull (; 返回truecircularQueue.deQueue (; 返回//truecircularqueue.enqueue(4)返回truecircularQueue.Rear (); 返回//4
提示:
所有值都在1000的范围内; 操作数将在1000的范围内。 请勿使用内置的队列库。
类mycircularqueue {
公共:
/* * initializeyourdatastructurehere.setthesizeofthequeuetobek.* /
mycircularqueue(intk ) {
x=new int[k 1];
三重=前端=0;
size=k 1;
}
/* * insertanelementintothecircularqueue.returntrueiftheoperationissuccessful.* /
OOLenqueue(intvalue ) )。
if(isfull ) )返回0;
x[trail]=value;
trail=(trail 1) % size;
返回1;
}
/* * deleteanelementfromthecircularqueue.returntrueiftheoperationissuccessful.* /
bool deQueue ()。
if(isempty ) ) return 0;
前端=(前端1 ) % size;
返回1;
}
/* * getthefrontitemfromthequeue.* /
int Front () }
if(isempty ) )返回- 1;
返回x [前];
}
/* * getthelastitemfromthequeue.* /
int Rear ()。
if(isempty ) )返回- 1;
返回轨迹==0? x [ size-1 ) : x [ (trail-1 ) % (size-1 ) ];
}
/* * checkswhetherthecircularqueueisemptyornot.* /
bool isEmpty () )。
if (前==trail )返回真;
返回假;
}
/* * checkswhetherthecircularqueueisfullornot.* /
bool isFull () }
if () trail1) % size==front )返回真;
返回假;
}
公共:
int *x;
int front;
int trail;
int size;
(;