1、原理
- 卡片游戏算法桌上有一叠牌,从第一张牌(即位于顶面的牌)开始从上往下依次编号为1~n。
- 当至少还剩两张牌时进行一下操作:把第一张牌扔掉,然后把第二张牌放到整叠牌的最后,以此往复。
- 输入卡牌数量n(可完成自动编号),输出每次扔掉的牌。
2、代码
#include<iostream>
using namespace std;
const int QueueSize = 100;
template < class T>
class CircleQueue
{
public:
CircleQueue() { front = rear = 0; }
void EnQueue(T x);
T DeQueue();
T GetFront();
int GetLength();
bool Empty() { return front == rear ? true : false; }
private:
int data[QueueSize];
int front;
int rear;
};
template < class T>
void CircleQueue<T>::EnQueue(T x)
{
if ((rear + 1) % QueueSize == front)
{
throw "overflow";
}
rear = (rear + 1) % QueueSize;
data[rear] = x;
}
template < class T>
T CircleQueue<T>::DeQueue()
{ if (rear == front)
throw"underflow";
front = (front + 1) % QueueSize;
return data[front];
}
template < class T>
T CircleQueue<T>::GetFront()
{
if (rear == front) throw"underflow";
return data[(front + 1) % QueueSize];
}
template < class T>
int CircleQueue<T>::GetLength()
{
return (rear - front + QueueSize) % QueueSize;
}
int main()
{ CircleQueue<int> a;
int m;
cin >> m;
for (int i = 0; i < m; i++)
{
a.EnQueue(i + 1);
}
while (a.GetLength() >= 2)
{
int temp = a.DeQueue();
cout << temp << " ";
int temp2 = a.DeQueue();
a.EnQueue(temp2);
}
cout << a.GetFront();
}
3、结果
