一、实验目的
1、掌握队列结构的定义与实现;
2、掌握队列结构的使用。
二、实验内容
1、题目描述:
首先创建队列类,采用数组描述;实现卡片游戏,假设桌上有一叠扑克牌,依次编号为1-n(从最上面开始)。当至少还有两张的时候,可以进行操作:把第一张牌扔掉,然后把新的第一张放到整叠牌的最后。输入n,输出最后剩下的牌。
输入输出格式:
输入:
一个整数n,代表一开始卡片的总数。
输出:
最后一张卡片的值。
#include<iostream>
using namespace std;
template <class T>
class arrayqueue
{
private:
int theFront;
int theBack;
int arrayLength;
int* queue;
public:
arrayqueue(int initialCapicity=10);
~arrayqueue(){
delete[] queue;}
bool empty() const {
return theFront==theBack;}
int size()const
{
return (theBack-theFront+arrayLength)%arrayLength;
}
int& front()
{
return queue[(theFront+1)%arrayLength];
}
int& back()
{
return queue[theBack];
}
void pop()
{
theFront=(theFront+1)%arrayLength;
~queue[theFront];
}
void push(const int& theElement);
};
template<class T>
arrayqueue<T>::arrayqueue(int initialCapacity)
{
arrayLength=initialCapacity;
queue=new T[arrayLength];
theFront=0;
theBack=0;
}
template<class T>
void arrayqueue<T>::push(const int&theElement)
{
if ((theBack + 1) % arrayLength == theFront)
{
T* newQueue = new T[2 * arrayLength];
int start = (theFront + 1) % arrayLength;
if (start < 2)
copy(queue + start, queue + start + arrayLength - 1, newQueue);
else
{
copy(queue + start, queue + arrayLength, newQueue);
copy(queue, queue + theBack + 1, newQueue + arrayLength - start);
}
theFront = 2 * arrayLength - 1;
theBack = arrayLength - 2;
arrayLength *= 2;
queue = newQueue;
}
theBack = (theBack + 1) % arrayLength;
queue[theBack] = theElement;
}
int main()
{
int n;
cin >> n;
arrayqueue<int> A;
for(int i=1;i<=n;i++)
{
A.push(i);
}
while(A.size()>=2)
{
A.pop();
A.push(A.front());
A.pop();
}
cout<<A.front();
}