|
谢谢了!程序有两部分:
//下面是类定义:
#ifndef CNODE_H
#define CNODE_H
#include<iostream>
using namespace std;
template<typename T>
class CNode
{
private:
CNode<T> *next;
public:
T data;
CNode(){};
CNode(const T& item);
void InsertAfter(CNode<T> *p);
CNode<T>* DeleteAfter();
CNode<T>* NextNode()const;
};
template<typename T>
CNode<T>::CNode(const T& item)
{
next=this;
data=item;
}
template<typename T>
void CNode<T>::InsertAfter(CNode<T> *p)
{
p->next=next;
next=p;
}
template<typename T>
CNode<T>* CNode<T>::DeleteAfter()
{
CNode<T> *tempPtr=next;
if(next==this)
return 0;
next=tempPtr->next;
return tempPtr;
}
#endif
//下面是CPP文件:
#include"cnode.h"
void CreateList(CNode<int> *header,int n)
{
CNode<int> *currPtr=header,*newNodePtr;
int i;
for(i=1;i<=n;i++)
{
newNodePtr=new CNode<int>(i);
currPtr->InsertAfter(newNodePtr);
currPtr=newNodePtr;
}
}
void Josephus(CNode<int> *list,int n,int m)
{
CNode<int> *prevPtr=list,*currPtr=list->NextNode();
CNode<int> *deleteNodePtr;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<m-1;j++)
{
prevPtr=currPtr;
currPtr=currPtr->NextNode();
if(currPtr==list)
{
prevPtr=currPtr;
currPtr=currPtr->NextNode();
}
}
cout<<"Delete person"<<currPtr->data<<endl;
deleteNodePtr=currPtr;
currPtr=currPtr->NextNode();
prevPtr->DeleteAfter();
delete deleteNodePtr;
if(currPtr==list)
{
prevPtr=currPtr;
currPtr=currPtr->NextNode();
}
}
cout<<endl<<"Person"<<currPtr->data<<"Win the cruise!"<<endl;
deleteNodePtr=list->DeleteAfter();
delete deleteNodePtr;
}
int main()
{
CNode<int> list;
int n,m=3;
cout<<"Enter the number of contestants ";
cin>>n;
CreateList(&list,n);
Josephus(&list,n,m);
return 0;
}
谢谢大家了。 |
|