这是C++的源码:
#include<iostream>
#include<limits>
using namespace std;
class NodeList
{
public:
struct Node
{ int value;
Node * prev;
Node * next;
};
NodeList(int nk);
~NodeList();
bool Run(int m);
private:
void Add(int val);
void Erase(void);
void Advance(int step);
Node head;
Node *cur;
int k;
};
NodeList::NodeList(int nk = 4)
{
head.prev = &head;
head.next = &head;
k = nk;
for (int i = 1;
i <= 2*k;
++i)
{ Add(i);
}
}
NodeList::~NodeList()
{
head.prev->next = &head;
while (head.next != &head)
{
Node *tmp = head.next;
head.next = tmp->next;
delete tmp;
}
}
void NodeList::Add(int val)
{
Node *tmp = new Node;
tmp->value = val;
if (head.next == &head) {
// have no data
head.next = tmp;
head.prev = tmp;
}
tmp->next = head.next;
tmp->prev = head.prev;
head.prev->next = tmp;
head.next->prev = tmp;
head.prev = tmp;
}
void NodeList::Erase()
{
Node *tmp = cur->next;
cur->prev->next = tmp;
tmp->prev = cur->prev;
// cout << "-R"
<< cur->value;
if (head.next == cur)
{
head.next = cur->next;
}
if (head.prev == cur)
{ head.prev = cur->prev;
}
delete cur;
cur = tmp;
}
void NodeList::Advance(int step)
{
for (int i = 1;
i < step;
++i)
{ cur = cur->next;
}
}
bool NodeList::Run(int m)
{
int i;
cur = head.next;
Advance(m);
i = 1;
while (cur->value > k)
{
Erase();
if (i == k) { return true;
}
Advance(m);
++i;
}
return false;
}
int main(int argc, char* argv[])
{
int k[4], m,count=0;
NodeList *list;
while(1)
{
cin >>k[count];
if(k[count]==0) break;
else
count++;
}
for(int i=0;i<count;i++)
{
#define MAX_M numeric_limits<int>::max()
for (m=k+1;
m<MAX_M;++m)
{
list = new NodeList(k);
if (list->Run(m) == true)
{
cout<<m<<endl;
delete list;
break;
}
delete list;
}
}
return 0;
}