实验内容:
假设桌上有一叠扑克牌,依次编号为1-n(从上至下)。当至少还有两张的时候,可以进行操作:把第一张牌扔掉,然后把新的第一张(原先扔掉的牌下方的那张牌,即第二张牌)放到整叠牌的最后。输入n,输出最后剩下的牌。
样例:
输入
100
输出
72
代码实现:
#include<iostream>
using namespace std;
class queue
{
public:
virtual ~queue() {}
virtual bool empty() const = 0;
virtual int size() const = 0;
virtual int& front() = 0;
virtual int& back() = 0;
virtual void pop() = 0;
virtual void push(const int& theElement) = 0;
virtual void output() = 0;
};
class extendedarrayQueue : public queue
{
public:
extendedarrayQueue(int initialCapacity = 10);
~extendedarrayQueue() { 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);
void initial(int n);
void output();
void play();
private:
int theFront;
int theBack;
int arrayLength;
int* queue;
};
extendedarrayQueue::extendedarrayQueue(int initialCapacity)
{
arrayLength = initialCapacity;
queue = new int[arrayLength];
theFront = 0;
theBack = 0;
}
void extendedarrayQueue::initial(int n) {
for (int i = 1; i <= n; i++) {
push(i);
}
}
void extendedarrayQueue::play() {
while (size() >= 2) {
pop();
int trans = front();
pop();
push(trans);
}
}
void extendedarrayQueue::push(const int& theElement)
{
if ((theBack + 1) % arrayLength == theFront)
{
int* newQueue = new int[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;
}
void extendedarrayQueue::output() {
for (int i = (theFront + 1) % arrayLength; i < (theFront + 1) % arrayLength + size(); i++) {
cout << queue[i];
}
cout << endl;
}
int main() {
int n;
cin >> n;
extendedarrayQueue A;
A.initial(n);
A.play();
A.output();
}