用循环链表解决Josehus问题
#include <iostream>
using namespace std;
struct CirLinkNode
{
int data;
struct CirLinkNode *link;
CirLinkNode(CirLinkNode *next = NULL):link(next) { }
CirLinkNode(int d, CirLinkNode *next = NULL):data(d), link(next) { }
};
class CircList
{
public:
CircList() { head = NULL; }
void create();
CirLinkNode* getHead() { return head; }
private:
CirLinkNode* head;
};
void CircList::create()
{
CirLinkNode *rear = NULL, *temp;
int n;
cin>>n;
while(n != 0)
{
temp = new CirLinkNode(n);
if (head == NULL)
{
head = temp;
rear = temp;
}else
{
rear->link = temp;
rear = temp;
}
cin>>n;
}
rear->link = head;
}
void Josephus(CircList& js, int n, int m)
{
int i, j;
CirLinkNode* pre = NULL;
CirLinkNode* current = js.getHead();
for (i = 0; i <n -1; i++)
{
for (j = 1; j < m; j++)
{
pre = current;
current = current->link;
}
cout<<(current->data)<<" ";
pre->link = current->link;
delete current;
current = pre->link;
}
}
int main()
{
CircList cir;
cir.create();
Josephus(cir, 8, 3);
}