问题描述:
//author [email protected]
#include <iostream>
using namespace std;
#include <unistd.h>
template<typename T>
class Node
{
template<typename U> friend Node<U>* makeList( U start , U end );
template<typename U> friend Node<U>* removeNodeBySteps ( Node<U> * list, int steps );
template<typename U> friend bool testJosephusLoop ( Node<U> * list );
public:
Node<T> (T &value);
Node<T> *getNext();
T & getValue ();
private:
Node *mNextNode ;
T mValue;
};
template<typename T>
Node<T>::Node(T &value)
{
mValue = value;
}
template<typename T>
Node<T> *
Node<T>::getNext()
{
return mNextNode;
}
template<typename T>
T &
Node<T>::getValue()
{
return mValue;
}
template<typename T>
Node<T> *
makeList(T start, T end)
{
Node<T> * firstNode = 0;
Node<T> * lastNode = 0;
Node<T> * currentNode = 0;
for ( T loop = start ; loop < end ; loop ++ )
{
if ( loop == start )
{
firstNode = new Node<T>(loop);
currentNode = firstNode;
continue;
}
else if ( loop < end )
{
Node<T> *tmpNode = new Node<T>(loop);
currentNode -> mNextNode = tmpNode;
currentNode = tmpNode;
}
}
lastNode = new Node<T>(end);
currentNode -> mNextNode = lastNode;
lastNode -> mNextNode = firstNode;
return lastNode;
}
template<typename U>
Node<U>*
removeNodeBySteps ( Node<U> * list, int steps )
{
int cnt = 0;
while ( true )
{
if ( list -> mNextNode == list )
{
cout << " the WINNER is " << list->mValue << endl ;
return list;
}
else
{
if ( cnt == steps - 1 )
{
Node<U> *nextNode = list->mNextNode;
cout << " the player is out " << nextNode->mValue << endl;
list->mNextNode = nextNode->mNextNode;
delete nextNode ;
nextNode = 0;
cnt = 0 ;
}
else
{
cnt ++ ;
list = list->mNextNode ;
}
}
}
}
template<typename U>
bool
testJosephusLoop( Node<U> * list )
{
if ( 0 == list )
{
return false;
}
Node<U> * firstNode = list ;
while ( true )
{
if ( list->mNextNode == firstNode )
{
return true;
}
else if ( list && list->mNextNode )
{
list = list -> mNextNode;
}
else if ( list || list->mNextNode )
{
return false;
}
}
return false;
}
void uniTest()
{
Node<int> * result = makeList(1,9);
bool check = testJosephusLoop(result);
cout << "check result "<< check <<endl;
removeNodeBySteps<int>(result,5);
Node<long> * result2 = makeList<long>(10,20);
bool check2 = testJosephusLoop(result2);
removeNodeBySteps(result2,3);
}
int main(int argc, char const *argv[])
{
uniTest();
return 0;
}