题目见http://poj.grids.cn/practice/2746/
解法:
#include<iostream>
using namespace std;
template<typename T>
struct Node
{
T value;
Node<T>* next;
Node(T data,Node<T>* n=NULL):value(data),next(n){};
};
class NodeList
{
public:
NodeList(int length):head(NULL),rear(NULL)
{
for(int i=1;i<=length;i++)
{
Node<int>* node = new Node<int>(i);
insert(node);
}
}
void insert(Node<int> * newNode)
{
if(isEmpty())
{
newNode->next=newNode;
head = newNode;
rear = newNode;
}
else
{
newNode->next = head;
rear->next = newNode;
rear = newNode;
}
}
Node<int>* josephusRemove(int interval)
{
Node<int> *p = head;
Node<int> *q = rear;
while(p->next!=p)
{
int count = 1;
while(count < interval)
{
q = p;
p = p->next;
count++;
}
if(head==p) head = p->next;
if(rear==p) rear = q;
q->next=p->next;
delete p;
p = q->next;
}
return p;
}
bool isEmpty()
{
return head==NULL;
}
~NodeList()
{
Node<int>* p = head;
Node<int>* q;
if(!isEmpty())
{
while(p->next!=head)
{
q = p;
p = p->next;
delete q;
}
delete p;
}
}
private:
Node<int>* head;
Node<int>* rear;
};
int main()
{
int m,n;
while(cin>>n>>m)
{
if(n==0&&m==0)break;
NodeList list(n);
Node<int>* p = list.josephusRemove(m);
cout<<p->value<<endl;
}
}